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);
...