我有一个PreferenceActivity类,用于处理我的应用程序中的首选项的获取和设置 . 但是我有一个“主”Activity类,它在启动时调用Web服务,并且基于Web服务的返回值,需要更新其中一个首选项 .
如果不抛出NullPointerException错误,我似乎无法工作 .
以下是主要活动的代码:
protected void onPostCreate(Bundle savedInstanceState)
{
if(getWebServiceResult.equals("FALSE"))
{
//do stuff
}
else
{
myPreferences prefs = new myPreferences();
prefs.updateMyChoice("TRUE");
}
}
以下是PreferenceActivity类中抛出错误的代码:
public void updateMyChoice(String newText)
{
if(subscriber_opt_in == null) //this is coming up null
{
subscriber_opt_in = (EditTextPreference) findPreference("opt_in"); //error here
}
subscriber_opt_in.setText(newText);
subscriber_opt_in.setSummary(newText);
}
我需要知道如何正确更新此首选项 . 如果有一种方法可以在主Activity类中进行,那就更好了,但是如果我必须通过PreferenceActivity类来完成它,我只需要了解如何做到这一点 .
谢谢!
1 回答
您应该使用SharedPreference类:http://developer.android.com/reference/android/content/Context.html#getSharedPreferences%28java.lang.String,%20int%29
代码示例并在此处使用:http://developer.android.com/guide/topics/data/data-storage.html#pref