Saving a List of Strings in Android with SharedPreferences

The SharedPreferences class allows you to save preferences specific to an android Application.

API version 11 introduced methods putStringSet and getStringSet which allows the developer to store a list of string values and retrieve a list of string values, respectively.

An example of storing an array of strings using SharedPreferences can be done like so:

// Get the current list.
SharedPreferences settings = this.getSharedPreferences("YourActivityPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
Set<String> myStrings = settings.getStringSet("myStrings", new HashSet<String>());

// Add the new value.
myStrings.add("Another string");

// Save the list.
editor.putStringSet("myStrings", myStrings);
editor.commit();

This method comes in handy when implementing a simple list of highscores that stores the last x number of scores.

6 thoughts on “Saving a List of Strings in Android with SharedPreferences

  1. Anze Reply

    Hi Mirza!
    I realize this is an old post, but I just want to point out to the future readers that your method does not work corrrectly.
    To update a set saved in shared preferences, you have to create a new Set object and put it in the editor instead of putting in the same (updated) object that you get from shared preferences.

    see:
    http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet(java.lang.String, java.util.Set)
    http://stackoverflow.com/questions/14034803/misbehavior-when-trying-to-store-a-string-set-using-sharedpreferences

  2. Patrick Reply

    Hi, Anze’s comment is correct. You cannot update a set saved in sharedpreferences the way that Mirza did in this post.

  3. Pingback: SharedPreferences cannot save data - BlogoSfera

  4. Pingback: SharedPreferences cannot save data - HTML CODE

Leave a Reply

Your email address will not be published. Required fields are marked *