Android Tricks and Tips: Storing a POJO Into Shared Preferences

Often you will yourself with the need for storing some simple persistent data in your Android application. Maybe you are tracking the last time you showed a user an upsell dialog? Perhaps you want to know if this is the first time onto a screen so you can show some new user experience flow.

Shared Preferences to the rescue! Sweet! All I need to do is store my Plain Old Java Object into a shared preference key and we are all set. So you open up the interface document for the Shared Preference editor class to see which method to call.

SharedPreferences Editor Interface

Wait a minute? I only see interfaces for basic Java types? No support for Parcelable or Serializable? Looks like there is no way to just store a POJO into Shared Preferences. Or is there…

GSON to the rescue! GSON is a beautiful Java utility library that allows converting to and from JSON and POJOs.

Saving to the Shared Preference

  1. Integrate the GSON library into your project. (Just download the jar and drag it into your libs folder)
  2. Create the POJO
  3. Serialize the POJO into a JSON String using GSON
  4. Save the serialized POJO into your shared preference

Restoring from the Shared Preference

  1. Read the shared preference value into a string
  2. Using GSON convert the serialized string back into your POJO

Time for Some Code!

First lets take a look at our class that we want to save and restore from a Shared Preference. What is important to notice is we have encapsulated the serialization and deserialization into the class.

Now lets take a look at the code to store and retrieve the POJO from the Shared Preference.

Interesting?

Do you find this sort of work interesting? Do you love quaint Bucks County Pennsylvania? Are you an amazing Android Developer? Then we would love to hear from you!

7 thoughts on “Android Tricks and Tips: Storing a POJO Into Shared Preferences”

  1. Hi,
    I need to serialize my custom pojo class which has [{},{},{}] Json Array of objects. I am using GSON for this custom pojo even I am getting response in that pojo object I just want to know how to make serialize this type of data.
    please help me !.
    sndpdevhare10@gmail.com

Leave a Reply

Your email address will not be published. Required fields are marked *