Put and get String array from shared preferences

Gabrielle picture Gabrielle · Nov 1, 2011 · Viewed 57k times · Source

I need to save on shared preferences some array of Strings and after that to get them. I tried this :

prefsEditor.putString(PLAYLISTS, playlists.toString()); where playlists is a String[]

and to get :

playlist= myPrefs.getString(PLAYLISTS, "playlists"); where playlist is a String but it is not working.

How can I do this ? Can anyone help me?

Thanks in advance.

Answer

Egor picture Egor · Nov 1, 2011

You can create your own String representation of the array like this:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < playlists.length; i++) {
    sb.append(playlists[i]).append(",");
}
prefsEditor.putString(PLAYLISTS, sb.toString());

Then when you get the String from SharedPreferences simply parse it like this:

String[] playlists = playlist.split(",");

This should do the job.