Android library written in Kotlin to simplify use of SharedPreferences.
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.cregus:simple-shared-prefs:1.0.2'
}
class AppPrefs(sharedPreferences: SharedPreferences) : SharedPrefs(sharedPreferences) {
var isAuthorized by booleanPreference()
var userName by stringPreference()
}
val appPrefs = AppPrefs(PreferenceManager.getDefaultSharedPreferences(context))
if (appPrefs.isAuthorized) {
appPrefs.userName = "John Doe"
}
You can use all data types that can be stored in shared preferences. Default values and delegates are:
Type | Value | Delegate |
---|---|---|
Boolean |
false |
booleanPreference() |
Int |
0 |
intPreference() |
Long |
0L |
longPreference() |
Float |
0f |
floatPreference() |
String |
null |
stringPreference() |
Set<String> |
null |
stringSetPreference() |
You can change default value by passing it to delegate method:
var isDarkTheme by booleanPreference(defaultValue = true)
String
and Set<String>
are nullable types until you provide default value, for example:
var userName: String? by stringPreference()
var themeColor: String by stringPreference(defaultValue = "#F44336")
You can also change preference key (it's property name by default) and switch from apply to commit save method:
var authToken by stringPreference(commit = true, key = "auth_token")
If you need to store other types of data you need to provide mapper:
object DateMapper : PreferenceMapper<Date, Long> {
override fun fromStored(stored: Long): Date {
return Date(stored)
}
override fun toStored(value: Date): Long {
return value.time
}
}
And now it can be stored using mapped version of delegate:
var lastUpdateCheck by mappedLongPreference(mapper = DateMapper, defaultValue = Date())