7 Mar 2012

Shared preference in Android

Hello Friends,

Android provides many ways of storing the data of an application. One of these ways is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key, value pairs.

Below is the full class which makes it easy to use in the app which covers almost all preferences.
Add below the line of code under the dependency of the build. Gradle file. You can its latest version.

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

Kotlin code snippet:


Create Share Preference:

  object AppPreference {

    const val PREF_NAME = "Pref_Name"
    const val KEY_NAMe = "UserName"

    private fun getPreferences(context: Context): SharedPreferences {
        return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
    }

    private fun getEditor(context: Context): SharedPreferences.Editor {
        return getPreferences(context).edit()
    }

    fun writeBooleanValue(context: Context,key: String?,value: Boolean)
    {
        getEditor(context).putBoolean(key, value).commit()
    }

    fun getBooleanValue(context: Context, key: String?,defValue: Boolean): Boolean
    {
        return getPreferences(context).getBoolean(key, defValue)
    }

    fun writeIntegerValue(context: Context,key: String?,value: Int)
    {
        getEditor(context).putInt(key, value).commit()
    }

    fun getIntegerValue(context: Context,key: String?,defValue: Int): Int
    {
        return getPreferences(context).getInt(key, defValue)
    }

    fun writeStringValue(context: Context,key: String?,value: String?)
    {
        getEditor(context).putString(key, value).commit()
    }

    fun getStringValue(context: Context,key: String?): String?
    {
        return getPreferences(context).getString(key, null)
    }

    /**
     * Saves object into the Preferences.
     *
     * @param object Object of model class (of type [T]) to save
     * @param key Key with which Shared preferences to
     **/
    fun <T> writeObjectValue(context: Context, key: String,obj: T) {
        //Convert object to JSON String.
        val jsonString = GsonBuilder().create().toJson(obj)
        getEditor(context).putString(key, jsonString).commit()
    }

    /**
     * Used to retrieve object from the Preferences.
     *
     * @param key Shared Preference key with which object was saved.
     **/
    inline fun <reified T> getObjectValue(mContext: Context, key: String): T? {
        //We get JSON String which was saved.
        val pref = mContext.getSharedPreferences(PREF_NAME, 0)
        val value = pref.getString(key, null)
        //JSON String was found which means object can be get.
        //We convert this JSON String to model object. Parameter "c" (of
        //type Class < T >" is used to cast.
        return GsonBuilder().create().fromJson(value, T::class.java)
    }

    fun clearAllPreference(context: Context)
    {
        getEditor(context).clear().commit()
    }
    fun clearPreference(context: Context,key: String)
    {
        getEditor(context).remove(key).commit()
    }
}
Store value into the Share preference:

1. Write String to the preference:
   AppPreference.writeStringValue(this, KEY, values)

2. Write Object to the preference:
   AppPreference.writeObjectValue(this, KEY, Object)

Retrieve data from the Preference:

 1. Retrieve String to the preference:
   AppPreference.getStringValue(this, KEY)

 2. Retrieve Object to the preference:
   val obj : ModelClass? = AppPreference.getObjectValue(this, KEY)

Clear the Preference:

 1. Clear the specific preference:
   AppPreference.clearPreference(contex, KEY)

 2. Clear all preference:
   AppPreference.clearAllPreference(context)

Java code snippet:


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

import com.google.gson.Gson;

import java.util.HashSet;
import java.util.Set;

import static android.content.Context.MODE_PRIVATE;
import static android.content.Context.MODE_WORLD_READABLE;
import static android.content.Context.MODE_WORLD_WRITEABLE;

/**
 * The {@link PreferencesManager} is a utility that is used to manage the preferences.
 */
public class PreferencesManager {

    private static SharedPreferences mSharedPreferences;
    private static Gson mGson;
    private static int INVALID_VALUE = -1;

    private Context mContext;
    private String mName;
    private int mMode;

    /**
     * Initial the preferences manager.
     * @param context The context of the application.
     */
    public PreferencesManager(Context context) {
        mContext = context;
        mGson = new Gson();
        mMode = INVALID_VALUE;
    }

    /**
     * Set the name of the preferences.
     * @param name The name of the preferences.
     */
    public PreferencesManager setName(String name) {
        mName = name;
        return this;
    }

    /**
     * Set the mode of the preferences.
     * @param mode The mode of the preferences.
     */
    public PreferencesManager setMode(int mode) {
        mMode = mode;
        return this;
    }

    /**
     * Initial the instance of the preferences manager.
     */
    public void init() {
        if (mContext == null) {
            return;
        }

        if (mName.isEmpty()) {
            mName = mContext.getPackageName();
        }

        if (mMode == INVALID_VALUE || (mMode != MODE_PRIVATE && mMode != MODE_WORLD_READABLE
            && mMode != MODE_WORLD_WRITEABLE)) {
            mMode = MODE_PRIVATE;
        }

        mSharedPreferences = mContext.getSharedPreferences(mName, mMode);
    }

    /**
     * Put a String value in the preferences editor.
     * @param key The name of the preference to modify.
     * @param value The new value for the preference.
     */
 public static void putString(String key, String value) {
        if (mSharedPreferences == null) {
            return;
        }

        Editor editor = mSharedPreferences.edit();
        editor.putString(key, value);
        editor.apply();
 }

    /**
     * Retrieval a String value from the preferences.
     * @param key The name of the preference to retrieve.
     * @param defValue Value to return if this preference does not exist.
     * @return Returns the preference values if they exist, or defValues.
     */
    public static String getString(String key, String defValue) {
        if (mSharedPreferences == null) {
            return defValue;
        }
        return mSharedPreferences.getString(key, defValue);
    }

    /**
     * Retrieval a String value from the preferences.
     * @param key The name of the preference to retrieve.
     * @return Returns the preference values if they exist, or defValues.
     */
 public static String getString(String key) {
  return getString(key, "");
 }

    /**
     * Put a set of String values in the preferences editor.
     * @param key The name of the preference to modify.
     * @param values The set of new values for the preference.
     */
    public static void putStringSet(String key, Set<String> values) {
        if (mSharedPreferences == null) {
            return;
        }

        Editor editor = mSharedPreferences.edit();
        editor.putStringSet(key, values);
        editor.apply();
    }

    /**
     * Retrieval a set of String values from the preferences.
     * @param key The name of the preference to retrieve.
     * @param defValues Values to return if this preference does not exist.
     * @return Returns the preference values if they exist, or defValues.
     */
    public static Set<String> getStringSet(String key, Set<String> defValues) {
        if (mSharedPreferences == null) {
            return defValues;
        }
        return mSharedPreferences.getStringSet(key, defValues);
    }

    /**
     * Retrieval a set of String values from the preferences.
     * @param key The name of the preference to retrieve.
     * @return Returns the preference values if they exist, or defValues.
     */
    public static Set<String> getStringSet(String key) {
        return getStringSet(key, new HashSet<String>());
    }

    /**
     * Put an int value in the preferences editor.
     * @param key The name of the preference to modify.
     * @param value The new value for the preference.
     */
 public static void putInt(String key, int value) {
        if (mSharedPreferences == null) {
            return;
        }

        Editor editor = mSharedPreferences.edit();
        editor.putInt(key, value);
        editor.apply();
 }


    /**
     * Retrieval an int value from the preferences.
     * @param key The name of the preference to retrieve.
     * @param defValue Value to return if this preference does not exist.
     * @return Returns the preference values if they exist, or defValues.
     */
    public static int getInt(String key, int defValue) {
        if (mSharedPreferences == null) {
            return defValue;
        }
        return mSharedPreferences.getInt(key, defValue);
    }

    /**
     * Retrieval an int value from the preferences.
     * @param key The name of the preference to retrieve.
     * @return Returns the preference values if they exist, or defValues.
     */
 public static int getInt(String key) {
  return getInt(key, 0);
 }

    /**
     * Put a float value in the preferences editor.
     * @param key The name of the preference to modify.
     * @param value The new value for the preference.
     */
 public static void putFloat(String key, float value) {
        if (mSharedPreferences == null) {
            return;
        }

        Editor editor = mSharedPreferences.edit();
        editor.putFloat(key, value);
        editor.apply();
    }

    /**
     * Retrieval a float value from the preferences.
     * @param key The name of the preference to retrieve.
     * @param defValue Value to return if this preference does not exist.
     * @return Returns the preference values if they exist, or defValues.
     */
    public static float getFloat(String key, float defValue) {
        if (mSharedPreferences == null) {
            return defValue;
        }
        return mSharedPreferences.getFloat(key, defValue);
    }

    /**
     * Retrieval a float value from the preferences.
     * @param key The name of the preference to retrieve.
     * @return Returns the preference values if they exist, or defValues.
     */
    public static float getFloat(String key) {
        return getFloat(key, 0);
    }

    /**
     * Put a long value in the preferences editor.
     * @param key The name of the preference to modify.
     * @param value The new value for the preference.
     */
 public static void putLong(String key, long value) {
        if (mSharedPreferences == null) {
            return;
        }

        Editor editor = mSharedPreferences.edit();
        editor.putLong(key, value);
        editor.apply();
 }

    /**
     * Retrieval a long value from the preferences.
     * @param key The name of the preference to retrieve.
     * @param defValue Value to return if this preference does not exist.
     * @return Returns the preference values if they exist, or defValues.
     */
    public static long getLong(String key, long defValue) {
        if (mSharedPreferences == null) {
            return defValue;
        }
        return mSharedPreferences.getLong(key, defValue);
    }

    /**
     * Retrieval a long value from the preferences.
     * @param key The name of the preference to retrieve.
     * @return Returns the preference values if they exist, or defValues.
     */
 public static long getLong(String key) {
  return getLong(key, 0);
 }

    /**
     * Put a boolean value in the preferences editor.
     * @param key The name of the preference to modify.
     * @param value The new value for the preference.
     */
 public static void putBoolean(String key, boolean value) {
        if (mSharedPreferences == null) {
            return;
        }

        Editor editor = mSharedPreferences.edit();
        editor.putBoolean(key, value);
        editor.apply();
 }

    /**
     * Retrieval a boolean value from the preferences.
     * @param key The name of the preference to retrieve.
     * @param defValue Value to return if this preference does not exist.
     * @return Returns the preference values if they exist, or defValues.
     */
    public static boolean getBoolean(String key, boolean defValue) {
        if (mSharedPreferences == null) {
            return defValue;
        }
        return mSharedPreferences.getBoolean(key, defValue);
    }

    /**
     * Retrieval a boolean value from the preferences.
     * @param key The name of the preference to retrieve.
     * @return Returns the preference values if they exist, or defValues.
     */
 public static boolean getBoolean(String key) {
  return getBoolean(key, false);
 }

    /**
     * Put a object in the preferences editor.
     * @param key The name of the preference to modify.
     * @param value The new value for the preference.
     */
    public static void putObject(String key, Object value) {
        if (mGson == null || value == null) {
            return;
        }

        putString(key, mGson.toJson(value));
    }

    /**
     * Retrieval a object from the preferences.
     * @param key The name of the preference to retrieve.
     * @param type The class of the preference to retrieve.
     * @return Returns the preference values if they exist, or defValues.
     */
    public static <T> T getObject(String key, Class<T> type) {
        if (mSharedPreferences == null || mGson == null) {
            return null;
        }
        return mGson.fromJson(getString(key), type);
    }

    /**
     * Remove a preference from the preferences editor.
     * @param key The name of the preference to remove.
     */
    public static void remove(String key) {
        if (mSharedPreferences == null) {
            return;
        }
        mSharedPreferences.edit().remove(key).apply();
    }

    /**
     * Remove all values from the preferences editor.
     */
    public static void clear() {
        if (mSharedPreferences == null) {
            return;
        }
        mSharedPreferences.edit().clear().apply();
    }

}
Below are the implementation Steps to use the above class in the development.

Steps 1: Initialize the preferences manager

   
    new PreferencesManager(this)
    .setName(name)
    .init();

Steps 2: Store and retrieve Values :

   // put int to preferences
      PreferencesManager.putInt(key, value);

    // get int from preferences
       PreferencesManager.getInt(key)
       or 
      PreferencesManager.getInt(key, defValue)
Steps 3: Store and retrieve Object :

   class Person {

    public String name;

    public Person(String name) {
        this.name = name;
    }
}

  // put object to preferences
     PreferencesManager.putObject(key, new Person(name));

  // get object from preferences
     PreferencesManager.getObject(key, Person.class);

You may like : 

Normal Share Preference: Example
Encrypted shared preferencesExample
Store & retrieve hashmap from the share preference: Example

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.

Thank you :)

No comments:

Post a Comment