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
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:
The result of the log will be
false
, and if you givetrue
as a default value, the result will betrue
because there is no value namedrandomBoolean
in the shared preferences so the default value is going to be returned.That’s why we need to give a default value.
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 offalse
, 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:
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
andgetStringSet
can both takenull
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 getnull
out of thegetString
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 atryGetString
one just to be consistent