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?
If you can guarantee your String
s 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.
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();
There is a method, putStringSet()
, in SharedPreferences.Editor
, which you can take advantage of if your strings are a Set
. (That is, no duplicates).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With