Save ArrayList<String> to persist [duplicate]

╄→гoц情女王★ 提交于 2019-12-14 03:38:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!