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

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
//To retrieve the value
//For Boolean value
//To retrieve the value
//For Int value
//To retrieve the value
//For Long value
//To retrieve the value

Accessing the data in the app

Android Developer | Flutter | Top Rated Freelancer ★