Reputation: 85
i keep getting NullPointerException on this line:
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
i ran some things through and i beleive that i have the wrong context as it is in a subpackage of the main package so i dont think it can reference the XML preference files. I have used this in class's that are in the main package with no trouble but for some reason this causes an exception.
Full code:
package schoolBook.Icestone.Expandable;
import schoolBook.Icestone.Days;
import schoolBook.Icestone.Main;
import schoolBook.Icestone.SetPreference;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class Lesson1 extends Lessons {
public Lesson1(String name) {
super(name);
//setGroup(" " + Days.getLessonarray(0) + " ");
String key = "W" + Main.getWeek() + "_" + SetPreference.xmlday + "_L" + SetPreference.xmllesson + "_Lesson";
System.out.println(key);
try {
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
String group = myPreference.getString(key, "def");
setGroup(" " + group + " ");
} catch (NullPointerException ex) {
ex.printStackTrace();
setGroup(" " + Days.getLessonarray(0) + " ");
}
}
}
Lesson.class extends Activity so think that may be the source of my problem but im not sure however i need this constructor in order to create the title of an expandable list view.
Any help would be greatly appreciated
if anyone could help shine some light on this problem it would be much appreciated
Upvotes: 1
Views: 2524
Reputation: 14746
You need to put this code into the Activity method onCreate. Activities cannot be instantiated as regular classes.
Put what you have in the constructor inside a method like this:
public void onCreate(Bundle bundles) {
}
Only like that, the Context will be available in a correct way and
this
will refer to a correct Context.
EDIT:
You could do something like this:
public Lesson1(String name, Context context) {
super(name);
SharedPreferences myPreference =
PreferenceManager.getDefaultSharedPreferences(context);
// Your other code
}
Upvotes: 4