Put and get String array from shared preferences
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.
You can use JSON to serialize your array as a string and store it in the preferences. See my answer and sample code for a similar question here:
How can write code to make sharedpreferences for array in android?
HashSet<String> mSet = new HashSet<>();
mSet.add("data1");
mSet.add("data2");
saveStringSet(context, mSet);
where
public static void saveStringSet(Context context, HashSet<String> mSet) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
editor.putStringSet(PREF_STRING_SET_KEY, mSet);
editor.apply();
}
and
public static Set<String> getSavedStringSets(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getStringSet(PREF_STRING_SET_KEY, null);
}
private static final String PREF_STRING_SET_KEY = "string_set_key";
From API level 11 you can use the putStringSet and getStringSet to store/retrieve string sets:
SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet(SOME_KEY, someStringSet);
editor.commit();
SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
Set<String> someStringSet = pref.getStringSet(SOME_KEY);