- Let's create a new project.
- 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:
Very useful, thanks!
Does MyObject need to implement Serializable in order of this method to work?
That is not required.
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 :)
Excellent example thanks for this
@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.
it is very useful and say me how to use multiple preferences...
a Serializable like class with Gson !Very good idea.
Thank you !
This tutorial is very useful.
Thank you..!!
Thanks, The Gson helps simplify things a lot, wasn't looking forward to getting my hands dirty with some ugly string manipulation hacks.
What if I "MyObject" has array of widgets on it?
Say for example:
TextView[] textViews;
How can I store and get the 'textViews'?
How would I use this to store/retrieve a credential from GoogleAccountCredential (New to android develeopment)?
Thanks in advance.
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.
really cool answer......... Love it..
After i press enter, the program Force Stop. Why?
When I debug the code , i get stack on the line Gson gson=new Gson();
Why?
Good work.............also get a detail tutorial with sample project at......http://androidtutorialsrkt.blogspot.in/
There Fit Library can do this
Save model as SharedPreferences(private static complex field not support)
https://github.com/2tu/fit
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
There is no Jar file at all in the download from github, how do I get the JAR?
Many thanks for sharing this post to us stick-rpg2.com
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.