Store And Retrieve Class Object In SharedPreferences

Please follow and like us:

Class Object In SharedPreference

Every Android developers need some simple solutions for Store and Retrieve Class Object in SharedPreferences. With the help of Android Complex Preferences library we can easily implement easy solution for storing and retrieving class object in SharedPreferences for our android apps. Let’s see how to store and retrive class object in SharedPreferences.

Store And Retrieve Class Object In SharedPreferences

We used Complex Preferences Library for store and retrieve class object in shared preference. “ComplexPreferences.java” contains main logic of store and retrive class object in sharedpreferences with the help of GSON library. In simple words Complex Preferences Library convert Class Object into JSON format  and retrieve back in Class Object from JSON format.

 

Add following class “ComplexPrefences.java” in your java package for store and retrive class object in SharedPreferences.

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;


/**
 * This class helps to store and retrive class object in the shared preferences
 */

public class ComplexPreferences {

	private static ComplexPreferences complexPreferences;
	private static Gson GSON = new Gson();
	Type typeOfObject = new TypeToken<Object>() {
	}.getType();
	private Context context;
	private SharedPreferences preferences;
	private SharedPreferences.Editor editor;

	private ComplexPreferences(Context context, String namePreferences, int mode) {
		this.context = context;
		if (namePreferences == null || namePreferences.equals("")) {
			namePreferences = "complex_preferences";
		}
		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 void clearObject() {
		editor.clear();
	}

	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 storaged with key " + key + " is instanceof other class");
			}
		}
	}


}

Add following library in your build.gradle dependency

compile 'com.google.code.gson:gson:2.3.1'

Create POJO Class for store and retrive your class object’s data using SharedPreferences.

import java.util.ArrayList;

public class ClassObject {
    
    // we can put all kind of data types
    // we can also store lists 
    
    private String username;
    
    private String password;
    
    private boolean isLogin;
    
    private int version;
    
    private ArrayList<String> hobbiesList;


    public ClassObject(String username, String password, boolean isLogin, int version) {
        this.username = username;
        this.password = password;
        this.isLogin = isLogin;
        this.version = version;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isLogin() {
        return isLogin;
    }

    public void setIsLogin(boolean isLogin) {
        this.isLogin = isLogin;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

Add Some Data in your Class

ClassObject classObject=new ClassObject("username","password",true,1);

We can Store Class Object in SharedPreferences like following way

    public static void setStatusList(ClassObject currentUser, Context ctx){
        ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "object_prefs", 0);
        complexPreferences.putObject("object_value", currentUser);
        complexPreferences.commit();
    }

We can Retrive Class Object in SharedPreferences like following way

  public static ClassObject getStatusList(Context ctx){
        ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "object_prefs", 0);
        ClassObject currentUser = complexPreferences.getObject("object_value", ClassObject.class);
        return currentUser;
    }

We can Clear Class Object in SharedPreferences like following way

   public static void clearCurrentUser( Context ctx){
        ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "object_prefs", 0);
        complexPreferences.clearObject();
        complexPreferences.commit();
    }

Hope you liked our Store And Retrieve Class Object In SharedPreferences Tutorial, if you have any trouble to implement Store And Retrieve Class Object In SharedPreferences tutorial in your app then contact me via chat here, love to answer your doubts.

nirav kalola