- 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.