Issue
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")
Solution
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
Answered By - cactustictacs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.