Reputation: 4981
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?
Upvotes: 63
Views: 65565
Reputation: 464
Store array list in prefrence using this easy function, if you want more info Click here
public static void storeSerializeArraylist(SharedPreferences sharedPreferences, String key, ArrayList tempAppArraylist){
SharedPreferences.Editor editor = sharedPreferences.edit();
try {
editor.putString(key, ObjectSerializer.serialize(tempAppArraylist));
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
And how to get stored array list from prefrence
public static ArrayList getSerializeArraylist(SharedPreferences sharedPreferences, String key){
ArrayList tempArrayList = new ArrayList();
try {
tempArrayList = (ArrayList) ObjectSerializer.deserialize(sharedPreferences.getString(key, ObjectSerializer.serialize(new ArrayList())));
} catch (IOException e) {
e.printStackTrace();
}
return tempArrayList;
}
Upvotes: 0
Reputation: 10212
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";
Upvotes: 4
Reputation: 5611
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);
Upvotes: 39
Reputation: 26149
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?
Upvotes: 9
Reputation: 40193
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.
Upvotes: 106