当应用程序被杀死时,共享首选项不保存StringSet(这是一项功能)

时间:2018-06-23 12:51:10

标签: android sharedpreferences android-sharedpreferences

我一直在将Set<String>加载并保存到Android的SharedPreferences上,在我测试杀死application并意识到未保存字符串集之前,它似乎还可以正常工作。

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();
}

我尝试过的一些事情:

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

1 个答案:

答案 0 :(得分:3)

在搜索失败后,我发现this-其他人也遇到了同样的问题。
他通过删除值并再次添加来解决了这个问题。
进一步阅读他的帖子评论揭示了原因,这是sharedPreferences.getStringSet文档:

  

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

所以我采用了稍微不同的方法,并创建了如下的新集合:

if (loadSubSet != null) {
    loadSubSet = new HashSet<>(loadSubSet);
...