Wrap SharedPreferences in an enum for easy access

Sometimes you need to share a couple of global preferences in your android application and one option is to use the SharedPreferences to accomplish this;

    //get the preferences

    SharedPreferences prefs = myActivity().getSharedPreferences(“ConfigurationStore”, Context.MODE_PRIVATE);

    //store a value

    prefs.edit().putString(“user”, “Teddy”).commit();

    //get the value

    prefs.getString(“user”, null); 

I like my code simple so I wrote a very simple wrapper to hide the above, here is the result.

    public enum ConfigurationStore {
      USER(“user”);
      private String key;
      private SharedPreferences prefs = //get this from your activity class
      ConfigurationStore(String key){
        this.key = key;
      }
      public String get(){
        return prefs.getString(key, null);
      }
      public void set(String value){
        prefs.edit().putString(key, value).commit();
      }

    }

The usage of the wrapper is shown below

    //Set a value:
    ConfigurationStore.USER.set("Teddy");
    //get a value
    ConfigurationStore.USER.get()

It’s easy to extend with new properties just by adding to the enum:

    public enum ConfigurationStore {
      USER(“user”),
      DEPLOYMENT_TYPE(“deployment_type”);
    ....
    //Set a value:
    ConfigurationStore.DEPLOYMENT_TYPE.set("Beta-test");
    //get a value
    ConfigurationStore.DEPLOYMENT_TYPE.get()

Note that this is strictly using Strings. Ideas how to extend this to support other primitives in a type safe way are most welcome!

Advertisements
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s