1

When I perform:

sharedPref.putString("id", null)

it comes up in my sharedPrefs file like this:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <boolean name="waiting" value="false" />
    <string name="state">initial</string>
    <string name="id"></string>
</map>

And when I try to retrieve it:

val id = sharedPref.getString("id", null) ?: return // doesn't return
Log.d(TAG, "id == blank: ${id.isBlank()}") // true

it says the value is blank and not null.

So if a string in sharedPrefs has been set to null, it will not actually be null? It will be blank ("").

I would like to make it null so it is easier to check with Kotlin's null safety - however I'm not sure if this is possible?

Zorgan
  • 8,227
  • 23
  • 106
  • 207
  • 2
    I think the abstraction here can be improved. Namely, what you're really checking is whether some data exists for a given key or not. `SharedPreferences` already has this built in with `contains(key: String)` which is semantically the same as getting back a `null` value. The fact that shared preferences are backed by an XML file is an implementation detail, if `get(key: String)` returns `null` you really have no way of knowing whether the key was explicitly set to `null` or whether `null` indicates that there no value exists for that key. – Sandi Oct 23 '19 at 22:26
  • I suggest if you want to "make it null", you should `remove` it from the shared preferences, not commit a null value. Then `contains` will work as Sandi commented above. – Tenfour04 Oct 24 '19 at 01:46
  • And example to above discussion https://stackoverflow.com/a/28789934/3496570 – Zar E Ahmer Oct 24 '19 at 06:26

1 Answers1

1

You can simply remove the entry from your SharedPreferences.

SharedPreferences.Editor editor = sharedPrefs.edit();
editor.remove("id");
editor.apply();

Now you can check with the following line if the entry exists:

if (sharedPrefs.contains("id")) {
    // entry exists
} else {
    // entry does not exist
}
josxha
  • 1,110
  • 8
  • 23