Android: Encapsulating Shared Preferences
The Android OS gives you a convenient way to save and load simple data (i.e. string, float, int, boolean and long) in the form of SharedPreferences. The data is stored in a dictionary format that utilizes a key/value pair. The “name” of the preferences is also supplied by your code. In a lot of the samples you’ll find online, the name of the shared preferences and all of the keys are stored as constants at the top of the Activity class (or worse, the key names are copy/pasted throughout the code!). I don’t like polluting my Activity classes with stuff like that so I’ve been encapsulating my preferences in their own class.
Here’s a simple preferences class that exposes a couple of pieces of data – Full name and Age:
package com.example;
import android.content.Context;
import android.content.SharedPreferences;
public class AppPrefs
{
private final static String ACCOUNT_PREFS_NAME = "prefs";
private final static String FULLNAME_KEYNAME = "FULLNAME_KEY";
private final static String AGE_KEYNAME = "AGE_KEY";
private final Context context;
private String fullName;
private int age;
public AppPrefs(Context ctx)
{
this.context = ctx;
SharedPreferences prefs = context.getSharedPreferences(ACCOUNT_PREFS_NAME, Context.MODE_PRIVATE);
fullName = prefs.getString(FULLNAME_KEYNAME, "unknown");
age = prefs.getInt(AGE_KEYNAME, 18);
}
public String getFullName()
{
return fullName;
}
public void setFullName(String name)
{
fullName = name;
}
public int getAge()
{
return age;
}
public void setAge(int number)
{
age = number;
}
public void Save()
{
SharedPreferences prefs = context.getSharedPreferences(ACCOUNT_PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString(FULLNAME_KEYNAME, fullName);
edit.putInt(AGE_KEYNAME, age);
edit.commit();
}
}
You can see it’s a very simple class, but it hides all the key names within the class. The main consumer of this class doesn’t need to know the name of the keys or even how the data is stored. By simply using the get/set methods and the Save() method, the Activity can concentrate on what it was designed to do. Imagine if we need to change where we’re storing the data? Maybe we’re moving from SharedPreferences to a SQLite database? In that case, we simply change the preferences class and the Activity won’t need any modifications.
I haven’t done a lot of Android programming yet, but so far, this technique has been working out well. I’ve created a sample application based on IntelliJ IDEA 10 using this technique on my bitbucket account.