I'm accessing my Android apps SharedPreferences
via
private val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)`
and then attempting to get data from it using
val lat: String = sharedPref.getString("MyKey", "Default")
But this line gives me an error reading "Type mismatch. Required String, found String?"
According to the documentation the second parameter in the getString method says "Value to return if this preference does not exist. This value may be null."
So what's the point of having a default value then if the value can be null? I cannot seem to get the default value to ever be used and the only way I can get my code to work is to use the elvis operator and rewrite my code as:
val lat: String = sharedPref.getString("MyKey", "Default") ?: "Default"
Which looks ugly. Am I crazy? What am I missing?
Consider this in a such way:
Every String
preference in SharedPreferences
can exist or not. So the code
val lat: String = sharedPref.getString("MyKey", "Default") ?: "Not Set"
will return:
Default
if the preference with this Key doesn't exists (means there is no mapping for this Key)Not Set
if the preference doesn't exists, and null
was passed as a default valuevalue
if the preference exists.This is because internally SharedPreferences
has this code:
String v = (String)mMap.get(key);
return v != null ? v : defValue;
It means that it will return null
only if we'll pass null
as a default value (and there were no value saved). This means we actually don't need an elvis option and we will not get "Not Set"
value unless we pass null
as a default value. And that is why this method returns nullable value, just because it allows you to pass nullable as a default value.