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

Shared Preferences not saving StringSet when application is killed (it's a feature)

我一直在加载 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();
}

我尝试过的一些事情:

经过一些不成功的搜索,我发现 this - 其他人遇到了同样的问题。
他通过删除值并再次添加来解决这个问题。
进一步阅读对他 post 的评论揭示了原因,这是 sharedPreferences.getStringSet 文档:

Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.

所以我采取了一种稍微不同的方法并创建了一个新的集合如下:

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