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”
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.
Hi, Anze’s comment is correct. You cannot update a set saved in sharedpreferences the way that Mirza did in this post.
Shared preference in android studio
Pingback: SharedPreferences cannot save data - BlogoSfera
Pingback: SharedPreferences cannot save data - HTML CODE
Hi dude, i have also find out one good example
Android Session Management Using SharedPreferences – Android Example