store and retrieve a class object in shared preference

androidGuy picture androidGuy · Mar 24, 2011 · Viewed 106k times · Source

In Android can we store an object of a class in shared preference and retrieve the object later?

If it is possible how to do it? If it is not possible what are the other possibilities of doing it?

I know that serialization is one option, but I am looking for possibilities using shared preference.

Answer

Parag Chauhan picture Parag Chauhan · Mar 23, 2013

Yes we can do this using Gson

Download Working code from GitHub

SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);

For save

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

For get

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Update1

The latest version of GSON can be downloaded from github.com/google/gson.

Update2

If you are using Gradle/Android Studio just put following in build.gradle dependencies section -

implementation 'com.google.code.gson:gson:2.6.2'