gpt4 book ai didi

java - getSharedPreferences 上的 Android SharedPreferences NullPointerException

转载 作者:行者123 更新时间:2023-11-29 22:11:06 30 4
gpt4 key购买 nike

我正在尝试创建一个类来处理存储和检索两个用户设置“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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com