Saturday, July 2, 2011

Store and Get an Object in Android Shared Preferences

Can I store and retrieve an object in Android Shared Preferences? Yes! This tutorial will walk you through a complete tutorial. Source code included! There are times when you need to store a lightweight object in Shared Preferences. I stress lightweight. We are going to use Google's JSON library to do the object serialization/de-serialization.
  • Let's create a new project.
Download the latest gson jar from http://code.google.com/p/google-gson/downloads/list. I am using version 1.7. Place the jar somewhere convenient (If I intend to use the jar in several projects, I will place in a folder outside of my project). For this example, I will create a new folder called "lib" inside the project folder. Place the jar you downloaded in "lib" folder. Now we need to add a reference to gson jar.
  • Open the project properties. Right click on project name "ObjectsInSharedPreferenceSample" or whatever you called your project and select "Properties"
  • Select "Java Build Path" > "Add External JARS..."

  • Let's add a custom class that we are going to store and retrieve in the Shared Preferences. Add a new class "MyObject"


  • To keep the example simple, lets add just two public properties to our "MyObject" class
    • public int myValue;
    • public String MyLabel;
  • Add two buttons and two EditText. Make sure to add the onClick directive the XML so when the button is pressed our methods are executed.






  • Let's write some code. In the MainActivity add the following method. This method will be called when the store button is pressed. It will create an instance of "MyObject" and set the "MyValue" string to what ever you type in the EditText inputEditText. Then it will convert the object to a string using the gson library and store that string in the SharedPreferences.
public void storeButton_Clicked(View v){
     EditText inputEditText = (EditText) findViewById(R.id.inputEditText);
     MyObject obj = new MyObject();
     obj.myValue = 2;
     obj.MyLabel = inputEditText.getText().toString();
     SharedPreferences appSharedPrefs = PreferenceManager
  .getDefaultSharedPreferences(this.getApplicationContext());
  Editor prefsEditor = appSharedPrefs.edit();
  Gson gson = new Gson();
  String json = gson.toJson(obj);
  prefsEditor.putString("MyObject", json);
  prefsEditor.commit();
  Toast.makeText(this, "Object stored in SharedPreferences", Toast.LENGTH_LONG);
    }

  • Now let's get the object from shared preferences and display it's properties in the outputEditText. 
public void getButton_Clicked(View v){
     EditText outputEditText = (EditText) findViewById(R.id.outputEditText);
  SharedPreferences appSharedPrefs = PreferenceManager
  .getDefaultSharedPreferences(this.getApplicationContext());
  Gson gson = new Gson();
  String json = appSharedPrefs.getString("MyObject", "");
  MyObject obj = gson.fromJson(json, MyObject.class);
  outputEditText.setText("obj.MyLabel: [" + obj.MyLabel + "] obj.MyValue: [" + obj.myValue + "]");
    }

Run the program. Save an object and retrieve it from SharedPreferences. To keep things as simple as possible I only included required code. There is a lot of code missing that you will want to add like error checking and running off the UI thread. But this will get you started.

Following is the complete source code for your review.

22 comments:

Sodman said...

Very useful, thanks!

GalDude33 said...

Does MyObject need to implement Serializable in order of this method to work?

Unknown said...

That is not required.

GalDude33 said...

Will I be able to store a RemoteViews object in Shared Preferences by this method?
Is there any limitation on the Objects you can store with this method?

Very nice blog by the way :)

BlueSkyCoding said...

Excellent example thanks for this

Unknown said...

@GalDude33 Hard to answer about limits. Since SharedPrefences are written in XML the only limit is the size of a file on Android. But obviously there are some practical limits.

avinash aitha said...

it is very useful and say me how to use multiple preferences...

Unknown said...

a Serializable like class with Gson !Very good idea.
Thank you !

j said...

This tutorial is very useful.
Thank you..!!

Lonely Coder said...

Thanks, The Gson helps simplify things a lot, wasn't looking forward to getting my hands dirty with some ugly string manipulation hacks.

Unknown said...

What if I "MyObject" has array of widgets on it?

Say for example:
TextView[] textViews;

How can I store and get the 'textViews'?

Unknown said...

How would I use this to store/retrieve a credential from GoogleAccountCredential (New to android develeopment)?

Thanks in advance.

Unknown said...

Hello Greg, I have an ArrayList which I want to save using SharedPreferences...
I guess I am able to save it using editor.PutString like this :

editor.putString("RecList", new Gson().toJson(RecipientArray).toString()); // where RecipientArray is the ArrayList containing Person objects.

I am not able to retrieve the ArrayList using new Gson().fromJson(json,RecipientArray);

Can you please advise on how can I save ArraylIst of Objects using the above tutorial.

Anonymous said...

really cool answer......... Love it..

Unknown said...

After i press enter, the program Force Stop. Why?

Unknown said...

When I debug the code , i get stack on the line Gson gson=new Gson();
Why?

Unknown said...

Good work.............also get a detail tutorial with sample project at......http://androidtutorialsrkt.blogspot.in/

Unknown said...

There Fit Library can do this

Save model as SharedPreferences(private static complex field not support)

https://github.com/2tu/fit

Unknown said...

Your blog is very useful for me, as your tutorial sessions are indeed of great benefit.
Android Training in Velachery | android development course fees in chennai

Mike said...

There is no Jar file at all in the download from github, how do I get the JAR?

Drag Racer V3 said...

Many thanks for sharing this post to us stick-rpg2.com

alicetaylor said...


Thank you for your post, I look for such article along time, today i find it finally. this post give me lots of advise it is very useful for me

http://lennyfacetext.com

Post a Comment

Note: Only a member of this blog may post a comment.