-7

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.

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
lcpr_phoenix
  • 373
  • 4
  • 15

1 Answers1

0

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

Abu Yousuf
  • 5,729
  • 3
  • 31
  • 50
  • if I use a for cycle to join all strings with a comma (,) it work the same as StringUtils.join()? because I prefer not to use a third party libraries. – lcpr_phoenix Feb 15 '18 at 23:22
  • If you manually join string using loop it will work same. You can use `TextUtils.join()` in `import android.text.TextUtils` package. Check here https://developer.android.com/reference/android/text/TextUtils.html#join(java.lang.CharSequence,%20java.lang.Object[]) – Abu Yousuf Feb 17 '18 at 14:15