I\'m accessing my Android apps SharedPreferences
via
private val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)`
SharedPreferences
is an abstraction over Key/Value databasing provided by Google, how you use it is up to you. If you dislike this syntax, then create a wrapper or extension for your getString()
. Just to give an example:
fun PreferenceManager.getStringTheFancyWay(key: String, defaultValue: String): String {
return getString(key, defaultValue) ?: defaultValue
}
val value = getStringTheFancyWay("a", "b")
Personally I dislike this, because null
allows for a better control flow over non-existing keys.
This is how I use SharedPreferences
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
val value = preferences.getString("username", null)
if (value != null) {
toast("Hello $value")
} else {
toast("Username not found")
}
or
preferences.getString("username", null)?.let { username ->
toast("Hello $username")
}
Notice the difference?