15

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.

Luke Taylor
  • 9,223
  • 13
  • 40
  • 72

3 Answers3

29

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.

Blundell
  • 73,122
  • 30
  • 204
  • 230
0

I use ObjectOutputStream to save lists to storage.

ObjectOutputStream oos = new ObjectOutputStream(new  FileOutputStream(your_file));
oos.writeObject(your_list);
oos.flush();
oos.close();

That should do it. It works for me

-2

If you want to store/retrieve/delete some string value in your program, then List is better than Array. Here below I will show you that how to use it.

 // Declaring List Variable
 List<String> Mylist = new ArrayList<String>();

 // Adding item to List
 Mylist.add(list.size(), "MyStringValue");   //this will add string at the next index

 // Removing element form list
 Mylist.remove(list.size()-1);   //this will remove the top most element from List
CDspace
  • 2,611
  • 17
  • 32
  • 36
Pir Fahim Shah
  • 9,985
  • 1
  • 75
  • 78