简体   繁体   中英

Android Shared Preferences with ArrayList

I'm trying to save and retrieve an ArrayList as shared preference.

I have three items in my ArrayList named arra ,but when I try to add the values in Set in the set.addAll(arr) , only two items get added.

Are there any corrections that can be one in the following code so I can save the arraylist correctly as shared preferences.

 SharedPreferences prefs = this.getSharedPreferences(filename,Context.MODE_PRIVATE);

                    Set<String> set = prefs.getStringSet(filename, null);
                    arra = new ArrayList<String>();
                    for (String str : set)
                       arra.add(str);

Saving of ArrayList

 SharedPreferences prefs=this.getSharedPreferences(filename,Context.MODE_PRIVATE);
        SharedPreferences.Editor edit=prefs.edit();

        Set<String> set = new HashSet<String>();
        set.addAll(arr);
        edit.putStringSet(filename, set);
        edit.commit();

The Set in java collections does not allow duplicate entries to be inserted and two out of the three items in your ArrayList are the same. This is the reason for only two of them being saved in the SharedPreferences.

You're trying to store boolean true and false values as strings. This means you can only have two possible strings, "true" and "false". Set type containers only store unique values - there are no duplicates. So in your set you will only have up to two different values, "true" and "false".

If you want to store a list, you might want to convert that into a string somehow so that the actual values and order are preserved. Then when reading that value out, parse the string to reconstruct the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM