How To Use Shared Preferences? The Easy And Fastest Way!

Abdul Rehman
2 min readDec 5, 2020

--

We all have to use shared preferences in our android app at some point. And every time we face this dilemma what is the fastest way to use shared preference.

Fear Not! In this post I will explain how I use Shared Preferences in my app with Kotlin Extenstion Functions and MVVM architecture.

Let's start with initial setup

Create Kotlin Class PrefRepository.kt and initialize the SharedPreferences for the call.

Once the PrefRepository.kt is created we can start adding our Kotlin Extension Function in the class. This function will help to reduce the boilerplate code in our class.

That It! Now we are ready to save our data in SharedPreferences. Before adding data in SharedPreferences we can create a separate file to store the variable names.

Now lets save our data!

We can add any type of data by calling the Extension function. We store value using put and retrieve value using get.

//For String value
VARIABLE_NAME.put(“value”)
//To retrieve the value
VARIABLE_NAME.getString()
//For Boolean value
VARIABLE_NAME.put(true)
//To retrieve the value
VARIABLE_NAME.getBoolean()
//For Int value
VARIABLE_NAME.put(15)
//To retrieve the value
VARIABLE_NAME.getInt()
//For Long value
VARIABLE_NAME.put(7.4)
//To retrieve the value
VARIABLE_NAME.getLong()

Accessing the data in the app

--

--