Place and get a String array from general settings

I need to save some array of strings on general settings and then get them. I tried this:

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

and get:

playlist= myPrefs.getString(PLAYLISTS, "playlists"); where the playlist is String , but it does not work.

How can i do this? Can anybody help me?

Thanks in advance.

+45
android string arrays sharedpreferences
Nov 01 2018-11-11T00:
source share
4 answers

You can create your own string representation of the array as follows:

 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 a String from SharedPreferences, just parse it like this:

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

That should do the job.

+70
Nov 01 2018-11-11T00:
source share

From API level 11 you can use putStringSet and getStringSet to store / retrieve sets of strings:

 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); 
+21
Mar 26 '15 at
source share

You can use JSON to serialize the array as a string and save it in settings. See my answer and sample code for a similar question here:

How to write code to create sharedpreferences for an array in android?

+7
Nov 01 '11 at 10:50
source share
 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"; 
0
Dec 23 '17 at 15:53
source share



All Articles