Android: SharedPreferences singleton to make life easier

I’ve noticed that a lot of projects have their SharedPreferences code scattered all over the project. The reason for this mostly is that fetching SharedPreference and reading/writing preferences as and when needed is the easiest thing to do when writing an app. Taking time to structure this bit properly would take time away from the original task and ain’t no one got time to refactor! Scattering SharedPreferences is problematic because keys/names for each preference may end up in a different place. This means that developers may not know that a preference already exists or may have a hard time finding the key/name for a preference they know should exist. Using dependency injection like Dagger2 resolves this issue to some extent, but you still have to rely on your developers to not scatter keys for preferences all over the place.

One solution to forcing developers to put all the SharedPreferences keys in the same place is using Enums as keys instead of Strings. However this would require you to write your own wrapper around SharedPreferences and provide getter and setter methods that take an enum instead of a String. While we are at it, we might as well make the code for reading and writing to SharedPreferences a Singleton (if we are not using dependency injection) since there is no point in repeating the same code all over your project.

Since performance is not (normally) a high priority with reading and writing preferences, I’ve made an Android Studio template that you can use to create a Singleton for your SharedPreferences. The code is on my gist[1] along with a Sample class incase you wish to not use Android Studio templates.

There are 2 templates and samples:

  1. SharedPreferences Singleton that uses String keys.
  2. SharedPreferences Single that uses Enum keys.

Personally I prefer to use Enum keys as I feel it enforces stricter control when there are multiple programmers working on a project. A programmer has no choice but to declare a new key in the appropriate enum class and so all the keys are in the same place.

However, when retrofitting old projects with a SharedPreference singleton it may not be possible to use enum keys and so a version that uses String keys may be more preferable.

Keep in mind that if your app uses more than 1 SharedPreference, by which I mean you use more than 1 setting name for your SharedPreferences, you can create Singleton class for each setting. This will make the code clear and easy to read.


One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.