【发布时间】:2012-11-17 22:14:14
【问题描述】:
我正在将 2 个字符串保存到共享首选项中,有时由于某种原因它们被删除了。 我知道在 stackoverflow 上还有其他几个问题,但没有一个对我有帮助..
我保存到共享首选项的方式有问题吗?
有没有人知道是什么导致了这个问题,它只发生了两次,比如 2 周之类的......所以我可以测试它,看看我是否已经解决了这个问题?
static void saveTitlePref(Context context, int mAppWidgetId, String text) {
SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, 0).edit();
editor.putString(PREF_PREFIX_KEY + mAppWidgetId, text);
editor.apply();
}
static void saveSizePref(Context context, int mAppWidgetId, String size) {
SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, 0).edit();
editor.putString(PREF_SIZE_PREFIX_KEY, size);
editor.apply();
}
我这样加载它们:
static String loadTitlePref(Context context, int mAppWidgetId) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String prefix = prefs.getString(PREF_PREFIX_KEY + mAppWidgetId, null);
// If there is no preference saved, get the default from a resource
if (prefix != null) {
return prefix;
} else {
return context.getString(R.string.appwidget_prefix_default);
}
}
static String loadSizePref(Context context, int mAppWidgetId) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String sizeprefix = prefs.getString(PREF_SIZE_PREFIX_KEY, null);
// If there is no preference saved, get the default from a resource
if (sizeprefix != null) {
return sizeprefix;
} else {
return "24";
}
}
【问题讨论】:
-
使用
editor.commit();而不是editor.apply(); -
这看起来不错,您是如何读取这些值的?
-
@MMohsinNaeem 胡。认为它几乎相同,但我会尝试它,看看它是否有效,谢谢..
-
@Jakob 你的
if (sizeprefix != null)检查是多余的,使用String sizeprefix = prefs.getString(PREF_SIZE_PREFIX_KEY, "24"); -
哦!现在我想起来了,说 commit() 而不是 apply() 可能会解决问题,因为我查看了我的应用程序的早期版本,我认为它没有这个错误,并且在那个版本中我使用了 commit (),不记得为什么改了..