java - getSharedPreferences 上的 Android SharedPreferences NullPointerException

标签 java android

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

加载“设置” Activity 后,出现空指针异常。

来自用户设置的 fragment :

    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();        
    }   
}

最佳答案

您的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);

关于java - getSharedPreferences 上的 Android SharedPreferences NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9622807/

相关文章:

android - wifi 关闭时不显示 GoogleMap v2

android - 如何在 2D 中使用 OpenGL ES 的折射功能?

java - 无法在真实设备上安装 apk

java - 如何将多维数组传递给构造函数?

java - ORA-01843 : not a valid month

java - Maven Eclipse Java 错误类型的层次结构...不一致

进入休眠模式后,Android Oreo 会杀死后台服务并清除未决警报和计划作业

android - 进度条阴影仅在填充部分

java - UnsatisfiedLinkError - native 库 - jnidispatch.dll

java - 列表数据包含其他列表中的所有确切数据