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:
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.