Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 应用程序终止时不保存StringSet的共享首选项(这是一项功能)_Android_Sharedpreferences_Android Sharedpreferences - Fatal编程技术网

Android 应用程序终止时不保存StringSet的共享首选项(这是一项功能)

Android 应用程序终止时不保存StringSet的共享首选项(这是一项功能),android,sharedpreferences,android-sharedpreferences,Android,Sharedpreferences,Android Sharedpreferences,我一直在加载一个集合并将其保存到Android的SharedReferences中,它似乎工作正常,直到我测试了杀死应用程序并意识到字符串集合没有保存 Set<String> stringSet = sharedPreferences.getStringSet(Constants.PREF_SHOULD_LOAD_SET, null); if (stringSet != null) { if (stringSet.contains(data)) { strin

我一直在加载一个
集合
并将其保存到Android的
SharedReferences
中,它似乎工作正常,直到我测试了杀死
应用程序
并意识到字符串集合没有保存

Set<String> stringSet = sharedPreferences.getStringSet(Constants.PREF_SHOULD_LOAD_SET, null);
if (stringSet != null) {
    if (stringSet.contains(data)) {
        stringSet.remove(data);
    } else {
        stringSet.add(data);
    }
    ...
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putStringSet(Constants.PREF_SHOULD_LOAD_SET, stringSet);
    editor.apply();
}
Set-stringSet=SharedReferences.getStringSet(Constants.PREF_SHOULD_LOAD_Set,null);
if(stringSet!=null){
if(stringSet.contains(数据)){
删除(数据);
}否则{
添加(数据);
}
...
SharedReferences.Editor=SharedReferences.edit();
编辑器.putStringSet(Constants.PREF_应_加载_集,stringSet);
editor.apply();
}
我尝试过的一些事情:

  • 使用提交(而不是应用)
  • 查看可能正在更改值的其他位置
  • 调试并查看值是否已保存

在我找到一些不成功的搜索后,其他人也有同样的问题。
他通过删除值并再次添加来解决此问题。
进一步阅读他的帖子的评论揭示了原因,这是
SharedReferences.getStringSet
文档:

请注意,您不能修改此调用返回的set实例。如果您这样做,则无法保证存储数据的一致性,也根本无法修改实例

因此,我采取了一种稍微不同的方法,创建了一个新的集合,如下所示:

if (loadSubSet != null) {
    loadSubSet = new HashSet<>(loadSubSet);
...
if(loadSubSet!=null){
loadSubSet=新哈希集(loadSubSet);
...