Home » Android » android – Save an arraylist of Strings to shared preferences

android – Save an arraylist of Strings to shared preferences

Posted by: admin May 14, 2020 Leave a comment

Questions:

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?

How to&Answers:

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();

Answer:

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.

Answer:

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

Answer:

If you are using an api (like level 8) where you cant use put/getStringSet(), then this is a possible solution, but this is very expensive and not flexible if you want to store bigger lists. I mean creating a map like datastructure for a simple array-like structure creates a huge overhead, if preformance is important.

To save it:

public static void writeList(Context context, List<String> list, String prefix)
{
    SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    int size = prefs.getInt(prefix+"_size", 0);

    // clear the previous data if exists
    for(int i=0; i<size; i++)
        editor.remove(prefix+"_"+i);

    // write the current list
    for(int i=0; i<list.size(); i++)
        editor.putString(prefix+"_"+i, list.get(i));

    editor.putInt(prefix+"_size", list.size());
    editor.commit();
}

To retrieve it:

public static List<String> readList (Context context, String prefix)
{
    SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);

    int size = prefs.getInt(prefix+"_size", 0);

    List<String> data = new ArrayList<String>(size);
    for(int i=0; i<size; i++)
        data.add(prefs.getString(prefix+"_"+i, null));

    return data;
}

And to actually use it:

List<String> animals = new ArrayList<String>();
animals.add("cat");
animals.add("bear");
animals.add("dog");

writeList(someContext, animals, "animal");

And to retrieve it:

List<String> animals = readList (someContext, "animal");

If you are not limited to use SharedPreferences, consider using SQLiteDatabase!