问题
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 app, example:
ArrayList<String> appSelected = new ArrayList<>();
appSelected.add("name_of_the_app");
Then the array is used for another purposes.
My question is: its posible to save the array? In the way that the user does not need to re-select the apps again when the application starts, like user preferences.
回答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 = null
if(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
来源:https://stackoverflow.com/questions/48801080/save-arrayliststring-to-persist