【发布时间】:2023-04-09 09:24:01
【问题描述】:
我正在尝试编写一个设置为共享首选项的字符串,乍一看它似乎可以工作。在应用程序的其他部分,我可以访问共享首选项并正确读取设置的字符串。
当我离开应用程序时,问题就来了。共享首选项字符串集中的所有数据都丢失了,它再次返回一个空集。
在应用程序关闭并重新打开之前我可以访问它,这一事实让我认为它存储在内存中而不是存储到磁盘中。
我在这里阅读了很多答案,尝试在提交和应用之间进行更改,但我不知道是什么导致了问题。
我尝试保存的方法是:
- 从共享首选项中检索哈希集
- 向哈希集添加新字符串
- 将更新的哈希集保存在共享首选项中。
代码如下:
public static void storeReminder (Context context, String reminderString){
// Get the set of reminder strings
SharedPreferences sharedPreferences = context.getSharedPreferences("AppData", Context.MODE_PRIVATE);
Set <String> remindersStringSet = sharedPreferences.getStringSet(context.getResources().getString(R.string.reminders_hashset_key), new HashSet<String>());
// Add the new reminder string to the reminder string set
remindersStringSet.add(reminderString);
// Save the reminder string set now that the new reminder string has been added
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet(context.getResources().getString(R.string.reminders_hashset_key), remindersStringSet);
editor.commit();
}
这就是我在应用程序的其他部分获取存储的哈希集的方式:
// Get the set of reminder strings
SharedPreferences sharedPreferences = context.getSharedPreferences("AppData", Context.MODE_PRIVATE);
Set<String> remindersStringSet = sharedPreferences.getStringSet(context.getResources().getString(R.string.reminders_hashset_key), new HashSet<String>());
提前感谢您的帮助
【问题讨论】:
-
你确定你使用 context.getSharedPreferences("AppData", Context.MODE_PRIVATE);在 get/set 中?
-
是的,当然。我编辑了我的问题以包括我在哪里检索它。
-
我会尝试将默认共享首选项切换为 PreferenceManager.getDefaultSharedPreferences(context) 而不是 context.getSharedPreferences("AppData", Context.MODE_PRIVATE) 除非您有特定理由使用单独的命名共享首选项在您的应用中
-
感谢尝试,没有任何区别