Android – SharedPreferences with serializable object

The accepted answer is misleading, we can store serializable object into SharedPreferences by using GSON. Read more about it at google-gson.

you can add GSON dependency in Gradle file with:

compile 'com.google.code.gson:gson:2.7'

Here the snippet:

First, create your usual sharedPreferences:

//Creating a shared preference
SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);

Saving from serializable object to preference:

 Editor prefsEditor = mPrefs.edit();
 Gson gson = new Gson();
 String json = gson.toJson(YourSerializableObject);
 prefsEditor.putString("SerializableObject", json);
 prefsEditor.commit();

Get serializable object from preference:

Gson gson = new Gson();
String json = mPrefs.getString("SerializableObject", "");
yourSerializableObject = gson.fromJson(json, YourSerializableObject.class);

Leave a Comment