Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android save List<String>

Tags:

android

list

save

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.

like image 666
Luke Taylor Avatar asked Jun 25 '12 17:06

Luke Taylor


1 Answers

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.

like image 83
Blundell Avatar answered Sep 20 '22 09:09

Blundell