skip to Main Content

I’m trying to put some data whose key: "isLoggedIn" and a value: true inside a shared preference file.
I do it this way…

sharedPreferences=getSharedPreferences(getString(R.string.preference_file_name), Context.MODE_PRIVATE)
 fun savePreferences(){
 sharedPreferences.edit().putBoolean("isLoggedIn",true).apply()
}

and then if I want to retreive/store this key-value pair inside a variable it allows me only when I give the second parameter which is a value or defualt value like this.

val isLoggedIn=sharedPreferences.getBoolean("isLoggedIn",false)

The question is why do I have to call the data by its name i.e., "isLoggedIn" and a default value in the getBoolean method instead of just calling it by the name like this code below.. ?

val isLoggedIn=sharedPreferences.getBoolean("isLoggedIn")

2

Answers


  1. There nothing ensure that there is an existing value named "isLoggedIn" in the shared preferences, so you need to provide that default value so incase there is no value named "isLoggedIn", there default value is going to be returned.

    You can try it by yourself by getting a boolean of a value that it doesn’t exist in your shared preferences and log the result, something like this:

    val randomBoolean = sharedPreferences.getBoolean("randomBoolean",false)
    Log.d("randomBoolean", "$randomBoolean")
    

    The result of the log will be false, and if you give true as a default value, the result will be true because there is no value named randomBoolean in the shared preferences so the default value is going to be returned.

    That’s why we need to give a default value.

    Login or Signup to reply.
  2. There’s also the contains function which checks if the key exists in the prefs (i.e. whether you’ve written a value for it or not) which can be useful if not set needs to be handled as a separate case. Maybe you need to be able to tell the difference between not set and a saved value of false, or -1 or whatever, or maybe there’s no natural default value you want to use (in this part of your logic at least – maybe something else handles that)

    You could write some extension functions if you like:

    fun SharedPreferences.tryGetBoolean(key: String): Boolean? =
        if (contains(key)) getBoolean(key, false) else null
    

    You’ll need one for each type you want to handle – you still need to pass a default to the get functions, but it’ll never be used.

    getString and getStringSet can both take null as a default, and you shouldn’t be able to store null as a value (putString() docs: Passing null for this argument is equivalent to calling remove(java.lang.String) with this key) so if you do get null out of the getString call you can assume it’s the default because the key didn’t exist. But if you’re going the extension function route, I’d probably still make a tryGetString one just to be consistent

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search