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.

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());

Posted on October 19, 2012, in Uncategorized and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: