Android SharedPreferences String Set - some items are removed after app restart

前端 未结 6 2018
南笙
南笙 2021-02-03 19:38

I save a string set in the shared preferences, if I read it out it\'s ok. I start other activities, go back and read it again, it\'s ok. If I close the application, and start it

6条回答
  •  故里飘歌
    2021-02-03 20:35

    Ran into this same problem. Solved it by clearing the editor after instantiating and before committing.

    sPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        sFavList = sPrefs.getStringSet(context.getResources().getString(R.string.pref_fav_key), null);
        sEditor = sPrefs.edit();
        sEditor.clear(); // added clear, now Set data persists as expected
        if (sFavList == null) sFavList = new HashSet<>();
        sFavList.add(title);
        sEditor.putStringSet(context.getResources().getString(R.string.pref_fav_key), sFavList).apply();
    

    I tried creating a copy as others suggested, but that didn't work for me.

    Found this solution here.

提交回复
热议问题