Save ArrayList to SharedPreferences

前端 未结 30 3553
野的像风
野的像风 2020-11-21 04:43

I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves

30条回答
  •  情歌与酒
    2020-11-21 05:04

    It's very simple using getStringSet and putStringSet in SharedPreferences, but in my case, I have to duplicate the Set object before I can add anything to the Set. Or else, the Set will not be saved if my app is force closed. Probably because of the note below in the API below. (It saved though if app is closed by back button).

    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. http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    SharedPreferences.Editor editor = prefs.edit();
    
    Set outSet = prefs.getStringSet("key", new HashSet());
    Set workingSet = new HashSet(outSet);
    workingSet.add("Another String");
    
    editor.putStringSet("key", workingSet);
    editor.commit();
    

提交回复
热议问题