Reputation: 85
I keep getting NullPointerException on this line:
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
I ran some things through and I believe that I have the wrong context as it is in a subpackage of the main package so I don't 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) + " ");
}
}
}
Lessons
class extends Activity so think that may be the source of my problem but im not sure.
File structure:
Icestone
if anyone could help shed some light on this problem it would be much appreciated
Upvotes: 5
Views: 3776
Reputation: 3590
You can't do this inside the constructor.
If it extends Activity Class it should't has a constructor, you need to handle that inside the oncreate method.
Upvotes: 4