Android Shared Preference Simplified

Balakrishnan
Tech Log
Published in
2 min readMay 26, 2020

We all have used shared preference once in a while to store simple data (Sometimes JWT too 🤫). Working with shared preference is not easy. Especially if you have multiple values and they are needed across the app.

Usually we keep all the keys somewhere in as Constants and access them where ever we want. But there we have to keep track of the data type. A call mismatch while reading the data could cause a crash at runtime.

What could go wrong with shared preference

So you could plan it to move all shared preference functions to a single class. Where you can refer the function to get and set value. It would solve the datatype mismatch.

This looks lot better than right. How ever, I find couple of problems in this code

  1. I have to write get() and set() functions for all the variable.
  2. We have to create a Unique key for each variable. Wait, We are creating a variable! Variable is unique in a Class. Why we cannot use the variable name to store the data?

This is where Kotlin’s ReadWriteProperty and Property Delegation comes handy.

The Delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively requiring zero boilerplate code.

We can write extension function which override the get() and set() in runtime to store and retrieve the data. The result will be like this .

As you can see we are not mentioning the Variable type or KEY value.

  1. Type of the variable is decided by the return type the extension function.
  2. Key name is refereed to the Variable name at runtime.

NOTE : You need to annotate the class with Keep or add proguard rule to skip renaming the variables in the file so that the variable name doesn’t change every time build is generated.

You can get the Kotlin extension file from here and source code here

--

--