Easier Android Shared Preferences in Kotlin

Tiago Reul
1 min readMar 6, 2021

--

Android provides a simple (and unprotected) key=value storage that can be used to persist user preferences and other non-critical data.

All the data stored in SharedPreferences should be considered PUBLIC even if they are accessed using the mode Context.MODE_PRIVATE, and by no means they should EVER be used to store password hashes (even salted), tokens or credit card information. Some people even argue that one should not use Android Shared Preferences AT ALL.

Nonetheless, you might decide (at your own risk 😛) to use this kind of store to keep some non-sensible data as language or filter preferences.

It’s easy enough to write or read from SharedPreferences:

Even so, if you repeat that snippet a dozen times, you will get quickly bored and end up making your code WET.

I’d rather access Shared Preferences like this (from some Activity, Fragment or Custom View):

And here’s the implementation that allows one to achieve that. For this example, I’ve implemented only a StringPref class to persist String values, but it’s simple enough to add similar classes to extend MyPreferences support for other primitive types.

One additional advantage of encapsulating your preferences in a separate class, as opposite to accessing SharedPreferences directly, is that you can decide later to exchange your storage from SharedPreferences to SQLite, Room, LevelDB or even a csv file as you will, keeping changes local to this class.

If you want to see all the code above in a complete example:

Thanks for reading.

Originally published at https://reul.space.

--

--

No responses yet