Android save List<String>

Yes exactly you can only save primitives so you could something like this:

List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

StringBuilder csvList = new StringBuilder();
for(String s : list){
      csvList.append(s);
      csvList.append(",");
}

sharedPreferencesEditor.put("myList", csvList.toString());

Then to create your list again you would:

String csvList = sharedPreferences.getString("myList");
String[] items = csvList.split(",");
List<String> list = new ArrayList<String>();
for(int i=0; i < items.length; i++){
     list.add(items);     
}

You could encapsulate this "serializing" into your own class wrapping a list to keep it nice and tidy. Also you could look at converting your list to JSON.

Tags:

List

Android

Save