Store a List or Set in SharedPreferences

I found the easiest solution to store and retrieve a list of items from SharedPreferences is to simply serialize / deserilaize the array into / from JSON and store it into a string setting.

Gson comes really handy doing it.

READ:

SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
String value = prefs.getString("list", null);

GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
MyObject[] list = gson.fromJson(value, MyObject[].class);

WRITE:

String value = gson.toJson(list);
SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
Editor e = prefs.edit();
e.putString("list", value);
e.commit();

Leave a Comment