Blog Archives

Android using SharedPreferences

Rather than having to call PreferenceManager.getDefaultSharedPreferences everytime in different activities, and have to keep track of all the keys in your application, it is easier to keep all preferences in one place. For that I create a wrapper class just for my preferences.

PreferencesClass.java

class PreferencesClass {
    static String preference_name = "my_preferences";
    static String preference_one = "preference_one";
    static String preference_two = "preference_two";
    static String preference_three = "preference_three";
    private static SharedPreferences getPreference(Context context){
        return PreferenceManager.getDefaultSharedPreferences(context);
    }

    public static int getPreferenceOne(Context context){ return getPreference(context).getInt(preference_one,0); }
    public static int setPreferenceOne(Context context, int value){ getPreference(context).edit().putInt(preference_one, value).commit(); }

public static int getPreferenceTwo(Context context){ return getPreference(context).getString(preference_two,null); }
    public static int setPreferenceTwo(Context context, string value){ getPreference(context).edit().putString(preference_two, value).commit(); }
    public static int getPreferenceThree(Context context){ return getPreference(context).getBoolean(preference_three,false); }
    public static int setPreferenceThree(Context context, boolean value){ getPreference(context).edit().putBoolean(preference_one, value).commit(); }

To use the method simply call the following in your activity

int preference_one = PreferencesClass.getPreferenceOne(getContext());
Advertisements