Kotpref, The Easier Way To Do Shared Preferences

Ari SWS
DOT Intern
Published in
2 min readJan 10, 2020

Sometimes in developing android apps, we need a local database to save data, such as user information, login information and etc. We can store data on local using SQLite, Object Box, Shared Preference, and many more. Think of a situation where you wanna save a small value (a flag probably) that you wanna refer later sometime when the user launches the application. Then shared preference is the best choice.

You may ask, we can do it using SQLite too right? Yep that’s right, but thesqliteproblem is that it’ll want you to write lengthy codes and supporting classes. Shared Preference let you read and write key-value pair in a couple of lines easily. But always remember, shared preference is not a solution for you to keep complex relational data.

If you want to use SharedPreferences and you are using Kotlin, then I suggest you do it with Kotpref Library. Why? Because it’s the easier way to do so.

Let’s find out!

How to use Kotpref

First of all, you need to add Kotpref dependency on your android project.

Add this line of code to your build.gradle file, and sync your project.

implementation 'com.chibatching.kotpref:kotpref:2.9.2'

After adding Kotpref to your android project, the things you need to do next is, call Kotpref.init(context) function in onCreate at Application class.

After that, we need to declare Kotpref Model. Create new Kotlin class named Profile.

And we have finished setting up Kotpref. Now you can store data into Kotpref easily using these lines of code

private fun saveData(){
Profile.name = editTextName.text.toString()
Profile.age = editTextAge.text.toString()
Profile.job = editTextJob.text.toString()
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show()
}

And to read the data, you can do it like this.

showName.text = "Name: " + Profile.name
showAge.text = "Age: " + Profile.age
showJob.text = "Job: " + Profile.job

And that’s it. It’s very simple, right? Now you can read and write data freely using KotPref.

You can see the sample project here

--

--