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.

Leave a Reply

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