Android save List<String>

Is there anyway I can save a List variable to the Androids phone internal or external memory? I know I can save primitive data, yet not sure about this one.

Thanks in advance.


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[i]);     
}

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.