Writing Singleton Class To Manage Android SharedPreferences

Proper Singleton Shared Preferences Class. it may help others in the future.

public class SharedPref
{
    private static SharedPreferences mSharedPref;
    public static final String NAME = "NAME";
    public static final String AGE = "AGE";
    public static final String IS_SELECT = "IS_SELECT";

    private SharedPref()
    {

    }

    public static void init(Context context)
    {
        if(mSharedPref == null)
            mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    public static String read(String key, String defValue) {
        return mSharedPref.getString(key, defValue);
    }

    public static void write(String key, String value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putString(key, value);
        prefsEditor.commit();
    }

    public static boolean read(String key, boolean defValue) {
        return mSharedPref.getBoolean(key, defValue);
    }

    public static void write(String key, boolean value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putBoolean(key, value);
        prefsEditor.commit();
    }

    public static Integer read(String key, int defValue) {
        return mSharedPref.getInt(key, defValue);
    }

    public static void write(String key, Integer value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putInt(key, value).commit();
    }
}

Simply call SharedPref.init() on MainActivity once

SharedPref.init(getApplicationContext());

Write data

    SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
    SharedPref.write(SharedPref.AGE, "25");//save int in shared preference.
    SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.

Read Data

    String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
    String age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
    String isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.

Output

Name : "XXXX";
Age : "25";
IsSelect : "true";

Leave a Comment