简体   繁体   English

SharedPreferences NullPointerException

[英]SharedPreferences NullPointerException

i keep getting NullPointerException on this line: 我一直在这一行得到NullPointerException:

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. 我运行了一些东西,我相信我有错误的上下文,因为它是在主包的子包中所以我不认为它可以引用XML首选项文件。 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. Lesson.class扩展了Activity,所以认为这可能是我的问题的根源,但我不确定但是我需要这个构造函数才能创建可扩展列表视图的标题。

Any help would be greatly appreciated 任何帮助将不胜感激

if anyone could help shine some light on this problem it would be much appreciated 如果有人能帮助对这个问题有所启发,我将不胜感激

You need to put this code into the Activity method onCreate. 您需要将此代码放入Activity方法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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM