How to store a List in SharedPreferences using Gson

First of all you have to download Gson library from here: https://code.google.com/p/google-gson/downloads/list

And then install it in your IDE..For Android Studio you can follow this article.. http://www.amedeobaragiola.me/blog/2013/09/02/how-to-import-jar-in-android-studio/

Then: (from stackoverflow)

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