Takao Chiba
Posted on November 21, 2017
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"
And call Kotpref.init(context)
function in onCreate
at Application class.
fun onCreate() {
super.onCreate()
Kotpref.init(this)
....
}
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)
}
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
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>
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
Posted on November 21, 2017
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 21, 2024