Home » Android » How to store class object in android sharedPreference?

How to store class object in android sharedPreference?

Posted by: admin June 15, 2020 Leave a comment


I would like to store class object in android sharedpreference. I did some basic search on that and I got some answers like make it serializable object and store it but my need is so simple. I would like to store some user info like name, address, age and boolean value is active. I made one user class for that.

public class User {
    private String  name;
    private String address;
    private int     age;
    private boolean isActive;

    public String getName() {
        return name;

    public void setName(String name) {
        this.name = name;

    public String getAddress() {
        return address;

    public void setAddress(String address) {
        this.address = address;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public boolean isActive() {
        return isActive;

    public void setActive(boolean isActive) {
        this.isActive = isActive;


How to&Answers:
  1. Download gson-1.7.1.jar from this link: GsonLibJar

  2. Add this library to your android project and configure build path.

  3. Add the following class to your package.

    package com.abhan.objectinpreference;
    import java.lang.reflect.Type;
    import android.content.Context;
    import android.content.SharedPreferences;
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
    public class ComplexPreferences {
        private static ComplexPreferences       complexPreferences;
        private final Context                   context;
        private final SharedPreferences         preferences;
        private final SharedPreferences.Editor  editor;
        private static Gson                     GSON            = new Gson();
        Type                                    typeOfObject    = new TypeToken<Object>(){}
    private ComplexPreferences(Context context, String namePreferences, int mode) {
        this.context = context;
        if (namePreferences == null || namePreferences.equals("")) {
            namePreferences = "abhan";
        preferences = context.getSharedPreferences(namePreferences, mode);
        editor = preferences.edit();
    public static ComplexPreferences getComplexPreferences(Context context,
            String namePreferences, int mode) {
        if (complexPreferences == null) {
            complexPreferences = new ComplexPreferences(context,
                    namePreferences, mode);
        return complexPreferences;
    public void putObject(String key, Object object) {
        if (object == null) {
            throw new IllegalArgumentException("Object is null");
        if (key.equals("") || key == null) {
            throw new IllegalArgumentException("Key is empty or null");
        editor.putString(key, GSON.toJson(object));
    public void commit() {
    public <T> T getObject(String key, Class<T> a) {
        String gson = preferences.getString(key, null);
        if (gson == null) {
            return null;
        else {
            try {
                return GSON.fromJson(gson, a);
            catch (Exception e) {
                throw new IllegalArgumentException("Object stored with key "
                        + key + " is instance of other class");
    } }
  4. Create one more class by extending Application class like this

    package com.abhan.objectinpreference;
    import android.app.Application;
    public class ObjectPreference extends Application {
        private static final String TAG = "ObjectPreference";
        private ComplexPreferences complexPrefenreces = null;
    public void onCreate() {
        complexPrefenreces = ComplexPreferences.getComplexPreferences(getBaseContext(), "abhan", MODE_PRIVATE);
        android.util.Log.i(TAG, "Preference Created.");
    public ComplexPreferences getComplexPreference() {
        if(complexPrefenreces != null) {
            return complexPrefenreces;
        return null;
    } }
  5. Add that application class in your manifest’s application tag like this.

    <application android:name=".ObjectPreference"
        android:theme="@style/AppTheme" > 
    ....your activities and the rest goes here
  6. In Your Main Activity where you wanted to store value in Shared Preference do something like this.

    package com.abhan.objectinpreference;
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    public class MainActivity extends Activity {
        private final String TAG = "MainActivity";
        private ObjectPreference objectPreference;
        protected void onCreate(Bundle savedInstanceState) {
        objectPreference = (ObjectPreference) this.getApplication();
        User user = new User();
        User user1 = new User();
        ComplexPreferences complexPrefenreces = objectPreference.getComplexPreference();
        if(complexPrefenreces != null) {
            complexPrefenreces.putObject("user", user);
            complexPrefenreces.putObject("user1", user1);
        } else {
            android.util.Log.e(TAG, "Preference is null");
  7. In another activity where you wanted to get the value from Preference do something like this.

    package com.abhan.objectinpreference;
    import android.app.Activity;
    import android.os.Bundle;
    public class SecondActivity extends Activity {
        private final String TAG = "SecondActivity";
        private ObjectPreference objectPreference;
        protected void onCreate(Bundle savedInstanceState) {
        objectPreference = (ObjectPreference) this.getApplication();
        ComplexPreferences complexPreferences = objectPreference.getComplexPreference();
        android.util.Log.i(TAG, "User");
        User user = complexPreferences.getObject("user", User.class);
        android.util.Log.i(TAG, "Name " + user.getName());
        android.util.Log.i(TAG, "Address " + user.getAddress());
        android.util.Log.i(TAG, "Age " + user.getAge());
        android.util.Log.i(TAG, "isActive " + user.isActive());
        android.util.Log.i(TAG, "User1");
        User user1 = complexPreferences.getObject("user", User.class);
        android.util.Log.i(TAG, "Name " + user1.getName());
        android.util.Log.i(TAG, "Address " + user1.getAddress());
        android.util.Log.i(TAG, "Age " + user1.getAge());
        android.util.Log.i(TAG, "isActive " + user1.isActive());
    }  }

Hope this can help you. In this answer I used your class for the reference ‘User’ so you can better understand. However we can not relay on this method if you opted to store very large objects in preference as we all know that we have limited memory size for each app in data directory so that if you are sure you have only limited data to store in shared preference you can use this alternative.

Any suggestions on this implement are most welcome.


the other way is to save each property by itself..Preferences accept only primitive types, so you can’t put a complex Object in it


You can use the global class

    public class GlobalState extends Application
   private String testMe;

     public String getTestMe() {
      return testMe;
  public void setTestMe(String testMe) {
    this.testMe = testMe;

and then Locate your application tag in nadroid menifest, and add this into it :


and you can set and get the data from any of your activity by using the following code.

     GlobalState gs = (GlobalState) getApplication();
     gs.setTestMe("Some String");</code>

      // Get values
  GlobalState gs = (GlobalState) getApplication();
  String s = gs.getTestMe();       


You could just add some normal SharedPreferences “name”, “address”, “age” & “isActive” and simply load them when instantiating the class


Simple solution of how to store login value in by SharedPreferences.

You can extend the MainActivity class or other class where you will store the “value of something you want to keep”. Put this into writer and reader classes:

public static final String GAME_PREFERENCES_LOGIN = "Login";

Here InputClass is input and OutputClass is output class, respectively.

// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";

// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();

// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);

Now you can use it somewhere else, like other class. The following is OutputClass.

SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");

// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);