Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save an arraylist of Strings to shared preferences

What is the best way to save an ArrayList of strings to SharedPreferences in API level 8? The only way i can think of now is to save all of the strings into one string separated by commas and save it that way. But I don't know if there is a maximum size for strings.

Is there a better way to do this?

like image 443
Peter Avatar asked Aug 27 '12 22:08

Peter


3 Answers

If you can guarantee your Strings in ArrayList don't contain comma, you can simply use

List<String> list = new ArrayList<String>();
...
editor.putString(PREF_KEY_STRINGS, TextUtils.join(",", list));

and to read the list

String serialized = prefs.getString(PREF_KEY_STRINGS, null);
List<String> list = Arrays.asList(TextUtils.split(serialized, ","));

You are limited by the memory of the device. It's good practice to use background thread to read/write shared preferences.

like image 132
biegleux Avatar answered Oct 31 '22 12:10

biegleux


I suggest you to save the arraylist as Internal Storage File in Android. For example for a arraylist named text_lines:

Internal storage File IO (Writing) :

try {
   //Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE
   FileOutputStream output = openFileOutput("lines.txt",MODE_WORLD_READABLE);
   DataOutputStream dout = new DataOutputStream(output);
   dout.writeInt(text_lines.size()); // Save line count
   for(String line : text_lines) // Save lines
      dout.writeUTF(line);
   dout.flush(); // Flush stream ...
   dout.close(); // ... and close.
}
catch (IOException exc) { exc.printStackTrace(); }

Interal storage File IO (Reading) :

FileInputStream input = openFileInput("lines.txt"); // Open input stream
DataInputStream din = new DataInputStream(input);
int sz = din.readInt(); // Read line count
for (int i=0;i<sz;i++) { // Read lines
   String line = din.readUTF();
   text_lines.add(line);
}
din.close();
like image 25
Ali Avatar answered Oct 31 '22 11:10

Ali


There is a method, putStringSet(), in SharedPreferences.Editor, which you can take advantage of if your strings are a Set. (That is, no duplicates).

like image 3
Jay Bobzin Avatar answered Oct 31 '22 13:10

Jay Bobzin