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.
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
.
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
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