DEV Community

Takao Chiba
Takao Chiba

Posted on

Kotpref: Easy SharedPreferences library for Kotlin android

Using SharedPreferences needs some little boilerplate code. And if we store much more data or include/exclude specific data from auto backup, we should consider to split XML file.
Kotpref is the library to make you realizing it simply and ease.

To install, just add app dependency in build.gradle.

compile "com.chibatching.kotpref:kotpref:2.2.0"
Enter fullscreen mode Exit fullscreen mode

And call Kotpref.init(context) function in onCreate at Application class.

fun onCreate() {
    super.onCreate()
    Kotpref.init(this)
    ....
}
Enter fullscreen mode Exit fullscreen mode

Kotpref requires defining data model to save into SharedPreferences. Data model can be created by extending KotprefModel like below.

object Profile : KotprefModel() {
    var name: String by stringPref()
    var age: Int by intPref(defuault = 20)
}
Enter fullscreen mode Exit fullscreen mode

You can now write and read by same way with normal property access!!

Profile.name = "chibatching" // write
println(Profile.name) // read -> chibatching

println(Profile.age) // read -> 20
Profile.age = 32 // write
println(Profile.age) // read -> 32
Enter fullscreen mode Exit fullscreen mode

Saved SharedPreferences XML through Kotpref is separated by Class name. At the above example, file name is Profile.xml and content is below.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="name">chibatching</string>
    <int name="age" value="32" />
</map>
Enter fullscreen mode Exit fullscreen mode

So, you can include/exclude each XML file (KotprefModel object) as auto backup target.

Kotpref core module only support basic SharedPreferences value type (String, Int, Long, Float, Boolean, String set). Although there are sub modules to support kotlin enum and gson serialized object.

Let's try if you develop Android application with kotlin!

Kotpref and I welcome to your contiribute! Please feel free to give your feedbacks!
https://github.com/chibatching/Kotpref

Top comments (2)

Collapse
 
n8ebel profile image
Nate Ebel

This is interesting. Can you specify the SharedPreferences file to use for particular KotprefModel? For example, a unique file for user settings and a unique file for onboarding state tracking?

Collapse
 
chibatching profile image
Takao Chiba • Edited

Thank you!

By default, file name is same as class name. But you can change it by overriding kotprefName
property.
If file name is fixed, just override it.

object Sample : KotprefModel() {
    override val kotprefName: String = "specific_name"
}

If name is dynamic, declare KotprefModel class with constructor parameter to init this property.

class Sample(override val kotprefName: String) : KotprefModel()