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

前端 未结 6 2001
南笙
南笙 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:38

    Try to create Copy of your set, and than you can save it in same prefs:

    private Set _setFromPrefs;
    
    
    public void GetSetFromPrefs()
    {
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
        Set someSets = sharedPref.getStringSet("some_sets", new HashSet() );
        _setFromPrefs = new HashSet<>(someSets); // THIS LINE CREATE A COPY
    }
    
    
    public void SaveSetsInPrefs()
    {
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putStringSet("some_sets", _setFromPrefs);
        editor.commit();
    }
    

提交回复
热议问题