getSharedPreferences上的Android SharedPreferences NullPointerException

时间:2012-03-08 18:26:14

标签: java android

我正在尝试创建一个单独的类来处理存储和检索两个用户设置'radius'和'cluster'。

加载'Settings'活动后,我得到一个空指针异常。

来自用户设置的

代码段

    storage = new Persistence();
    radius = (EditText) findViewById(R.id.etRadius);        
    radius.setText(String.valueOf(storage.getRadius()));  <-- Problem

处理持久性的类:

public class Persistence extends Activity { 

    private static final String PREFERENCES = "tourist_guide_preferences";
    private SharedPreferences settings;
    private SharedPreferences.Editor editor;

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        settings = getSharedPreferences(PREFERENCES, 0);
        editor = settings.edit();
    }

    public int getRadius()
    {
        return settings.getInt("radius", 2000);
    }

    public int getClusterSize()
    {
        return settings.getInt("cluster", 50);
    }

    public void setRadius(int radius)
    {
        editor.putInt("radius", radius);
        editor.commit();
    }

    public void setClusterSize(int size)
    {
        editor.putInt("cluster", size);
        editor.commit();        
    }   
}

2 个答案:

答案 0 :(得分:1)

您的Persistence课程不应该是Activity。您应该将它设为普通类,并将其onCreate的代码放在此普通类构造函数中。

将其更改为:

public class Persistence { 

    private static final String PREFERENCES = "tourist_guide_preferences";
    private SharedPreferences settings;
    private SharedPreferences.Editor editor;
    private Context context;


    public Persistence(Context context)
    {
        this.context = context;
        settings = context.getSharedPreferences(PREFERENCES, 0);
        editor = settings.edit();
    }

    public int getRadius()
    {
        return settings.getInt("radius", 2000);
    }

    public int getClusterSize()
    {
        return settings.getInt("cluster", 50);
    }

    public void setRadius(int radius)
    {
        editor.putInt("radius", radius);
        editor.commit();
    }

    public void setClusterSize(int size)
    {
        editor.putInt("cluster", size);
        editor.commit();        
    }   
}

在您的Activity中,您实例化此Persistence类,如下所示:

storage = new Persistence(this);

答案 1 :(得分:1)

storage = new Persistence();这不会调用Persistence活动的onCreate。 你创建一个通用类会更好。您创建一个上下文变量并使用它来创建共享首选项实例。您应该从活动类

中调用此通用类