8

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;
    }
}

Thanks.

5 Answers5

18
  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>(){}
                                                                    .getType();
    
    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() {
        editor.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;
    
    @Override
    public void onCreate() {
        super.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:allowBackup="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" > 
    ....your activities and the rest goes here
    </application>
    
  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;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        objectPreference = (ObjectPreference) this.getApplication();
    
        User user = new User();
        user.setName("abhan");
        user.setAddress("Mumbai");
        user.setAge(25);
        user.setActive(true);
    
        User user1 = new User();
        user1.setName("Harry");
        user.setAddress("London");
        user1.setAge(21);
        user1.setActive(false);
    
        ComplexPreferences complexPrefenreces = objectPreference.getComplexPreference();
        if(complexPrefenreces != null) {
            complexPrefenreces.putObject("user", user);
            complexPrefenreces.putObject("user1", user1);
            complexPrefenreces.commit();
        } 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;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    
        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.

  • how can i get a arraylist as an object if i am saving it as Arraylist of a type using this – Pankaj Nimgade Apr 30 '15 at 10:42
  • 1
    @PankajNimgade You can set your arrayList to object but make sure you can serialize your object contains in arrayList. Moreover, you can make it parcelable and directly pass it to intent. –  May 31 '15 at 11:20
  • @user456118 Hi, your answer is best till I have found, works like charm, just I need one modification, if the user has been logged in once then it should not display login screen and it should directly show the mainactivity screen. Please help me out with this... – amit pandya Feb 12 '18 at 12:28
1

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

Tomislav Novoselec
  • 4,570
  • 2
  • 27
  • 22
1

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 :

  android:name="com.package.classname"  

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();       
Priya
  • 1,763
  • 1
  • 12
  • 11
0

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

Dhanesh Budhrani
  • 190
  • 3
  • 15
0

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);
editor.commit();

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);
Zly-Zly
  • 167
  • 2
  • 8