NullPointerException getDefaultSharedPreferences()

R3M*_*MIX 5 java android nullpointerexception sharedpreferences

我一直在这行上得到NullPointerException:

SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
Run Code Online (Sandbox Code Playgroud)

我运行了一些东西,我相信我有错误的上下文,因为它在主包的子包中,所以我不认为它可以引用XML首选项文件.我已经在主程序包中的类中使用了这个,没有任何问题,但由于某种原因,这会导致异常.

完整代码:

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) + " ");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Lessons class extends Activity所以认为这可能是我的问题的根源,但我不确定.

文件结构:

Icestone

  • Main.class和其他一些使用共享首选项的类,它工作正常
    • 课程包(第1课和课程在此包中)
  • 带有首选项的XML文件夹

如果有人能帮助阐明这个问题,我将不胜感激

Pan*_*hro 4

您不能在构造函数内执行此操作。

如果它扩展了 Activity 类,则它不应该有构造函数,您需要在 oncreate 方法内处理它。