如何从 PreferenceActivity 获取 SharedPreferences
How to get SharedPreferences from a PreferenceActivity
我有一个 class,我想在其中获取保存在 Android 应用的 PreferencesActivity 中的 SharedPreferences。我已经试过了,但它给出了一个空指针异常。同样,我使用 class,而不是 activity 来获得我需要的东西。
public PrefsInterface(Context context)
{
gson = new Gson();
sPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String json = sPreferences.getString("myJsonCity", "");
if(!json.isEmpty())
{
Type t = new TypeToken<CityObj>(){}.getType();
myCity = gson.fromJson(json, t);
//System.out.println(myCity.city());
}
else
{
System.out.println("Error getting city from settings.");
}
}
我明白了为什么我没有得到任何东西。我在保存错误的东西。而不是像这样保存:
SharedPreferences preferences==PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("Name","Harneet");
editor.commit();
我是这样保存的:
SharedPreferences.Editor = this.getPreferences(MODE_PRIVATE).edit();
这意味着我无法检索由于该隐私模式而保存的设置。
我有一个 class,我想在其中获取保存在 Android 应用的 PreferencesActivity 中的 SharedPreferences。我已经试过了,但它给出了一个空指针异常。同样,我使用 class,而不是 activity 来获得我需要的东西。
public PrefsInterface(Context context)
{
gson = new Gson();
sPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String json = sPreferences.getString("myJsonCity", "");
if(!json.isEmpty())
{
Type t = new TypeToken<CityObj>(){}.getType();
myCity = gson.fromJson(json, t);
//System.out.println(myCity.city());
}
else
{
System.out.println("Error getting city from settings.");
}
}
我明白了为什么我没有得到任何东西。我在保存错误的东西。而不是像这样保存:
SharedPreferences preferences==PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("Name","Harneet");
editor.commit();
我是这样保存的:
SharedPreferences.Editor = this.getPreferences(MODE_PRIVATE).edit();
这意味着我无法检索由于该隐私模式而保存的设置。