What's the point of having a default value in sharedPref.getString?

后端 未结 4 1984
一个人的身影
一个人的身影 2021-01-17 19:41

I\'m accessing my Android apps SharedPreferences via

private val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)`

4条回答
  •  不知归路
    2021-01-17 20:12

    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?

提交回复
热议问题