Save Arraylist To Persist
My app let the user to select from a list of various apps instaled in the device, if the user selecct one or more options each selection its saved in a ArrayList as the name of the
Solution 1:
You can save ArrayList<String> in SharedPreference. You can not directly store a ArrayList in SharedPreference. As your list contains only Stringand String are Serializable so you can convert the list items into String with some joind delimiter. Then save to SharedPreference as a String.
To retrieve it get String from SharedPreference and split it with the delimiter.
This solution will only work if your String don't have any comma(,)
//String joinStr = StringUtils.join(stringList, ",");
String joinStr = TextUtils.join(",", stringList);
editor.putString(PREF_KEY_LIST_STRINGS, joinStr).commit();
And to retrieve
String restoredStr= prefs.getString(PREF_KEY_LIST_STRINGS, null);
List<String> restoredList = nullif(restoredStr!= null){
restoredList = Arrays.asList(restoredStr.split(","));
}
This will only work for String type ArrayList.
SharedPreference is mainly used for simple data. If you are working with lots of data then consider using Sqlite
Post a Comment for "Save Arraylist To Persist"