我试图理解android的sharedpreferences。我是个初学者
对这件事不太了解。
我为我的应用程序首选项实现了这个类
public class Preferences {
public static final String MY_PREF = "MyPreferences";
private SharedPreferences sharedPreferences;
private Editor editor;
public Preferences(Context context) {
this.sharedPreferences = context.getSharedPreferences(MY_PREF, 0);
this.editor = this.sharedPreferences.edit();
}
public void set(String key, String value) {
this.editor.putString(key, value);
this.editor.commit();
}
public String get(String key) {
return this.sharedPreferences.getString(key, null);
}
public void clear(String key) {
this.editor.remove(key);
this.editor.commit();
}
public void clear() {
this.editor.clear();
this.editor.commit();
}
}
问题是我想设置默认的首选项。它们将在安装应用程序时设置,并可在安装后由应用程序修改,并保持持久性。
我听说了preferences.xml,但我不了解这个过程。
有人能帮我吗?
谢谢你的时间
最佳答案
很简单,如果您希望每个变量都有一个单独的默认值,您需要为每个变量都这样做,但是在您的方法上:
public String get(String key) {
return this.sharedPreferences.getString(key,"this is your default value");
}
如果变量从未被用户访问过或从未创建过,则系统会将默认值设置为值,如果您或用户更改了此值,则将忽略默认值。参阅http://developer.android.com/guide/topics/data/data-storage.html#pref
直接从Android文档:
sharedpreferences类提供了一个通用框架,允许
保存和检索原语数据的持久键值对
类型。您可以使用sharedpreferences保存任何原始数据:
布尔、浮点、整数、长和字符串。这些数据将持续存在
跨用户会话(即使您的应用程序被终止)。