Share & Follow

Get new posts when they come!

Thank you for subscribing.

Something went wrong.

[Tutorial] How to use SharedPreferences in Kotlin

Android development can be (and usually is) much easier and satisfying with Kotlin, compared to Java. But it’s also quite different. Lots of things, like predefined nullability (or lack of it), no static as we know it, extension and top-level functions are there to be used in our favor. No wonder that it may be confusing what approach to choose, especially when the same thing can be done in different ways.

Today I’m gonna present you a better way of initializing and using SharedPreferences in your Kotlin app. No more repeating code with initialization in every place you want to get a preference, no more long lines to get or set a pref. How to accomplish this? Use object with lateinit and custom getters & setters.

Create a new object called AppPreferences. As objects in Kotlin have, the instance of it will be created on first use and we’ll have only one in our app. So, kind of like a singleton in Java, but without all the worry about thread-safety.

We still need a context to get preferences though, that’s why we can’t initialize it right away. Objects can’t have constructors, so create init() function with a context param. I have also added an extension function edit(), just to have less of a repeating code. firstRun is an example preference of Boolean type. You can add as many as you wish inside the object. You just override get() and set() methods and, magically, reading and writing is easy like x = false. Great!

The preferences itself get initialized in Application’s onCreate() method, which is called only on first app’s run. So, create a new Kotlin class, extend Application and initialize our AppPreferences, like so: