Search code examples
androidarraysstringsharedpreferences

Put and get String array from shared preferences


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?


Solution

  • 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.