SharedPreferences

watch out when using Activity.getPreferences()!

The Android SDK has a handy little method for getting SharedPreferences -- the Activity class has a getPreferences() method that implicitly opens/creates a preferences file named after the simple class name of the Activity (e.g. "MyActivity"). Cool, it works.  Ship it.

OK, now in version 2, you add a new Activity called MyOtherActivity, and want to access those same preferences.  Hmm, you can't use getPreferences() in MyOtherActivity; that would use a different filename.  So, you have to use (from the Context class) getSharedPreferences(MyActivity.class.getSimpleName(), ...) instead.

A little ugly.  But wait, it gets worse.

Maybe later, you decide to rename MyActivity to ABetterNameForMyActivity.  Now things are really a nuisance, because you can't use getPreferences() inside MyActivity anymore, and the hack in MyOtherActivity won't work, either (in an upgrade scenario, the new version of the app won't use the preference file left over from the previous version).

You can replace both usages to use Context.getSharedPreferences("MyActivity", ...), i.e. explicitly specify the name of the no-longer-existing activity, but that's going to be pretty confusing to the next guy who looks at the code.

So, to avoid all this, my recommendation is to create a helper class right from the beginning that encapsulates the name of the preference file (which would be unrelated to any particular Activity).  This would also be a good place to define static Strings for the preference value names used when getting and setting preference values.  Something like this (a little crude, but you get the idea):


public class SharedPrefs { 
    public static String PREF_VALUE1 = "value1";
    public static String PREF_VALUE2 = "value2";

    private static String prefsFileName = "prefs"; 
    private SharedPreferences prefs;

    public SharedPrefs(Context context) { 
        prefs = context.getSharedPreferences(prefsFileName, Context.MODE_PRIVATE); 
    }

    public SharedPreferences getPreferences() { 
        return prefs; 
    }
}