Home > Back-end >  False positive "SharedPreferences.edit() without a corresponding commit() or apply() call"
False positive "SharedPreferences.edit() without a corresponding commit() or apply() call"

Time:03-31

I got a lint warning on EVERY (already existing) sharedPreferences.edit() call after updating Android Studio to Bumblebee 2021.1.1 Patch 2 from 4.2.1

What's interesting, is that when I use it like this, I get the warning:

sharedPreferences.edit()
.putBoolean("example", true)
.apply()

But when I save it in a variable like this, I get no warning:

val sharedPrefEdit = sharedPreferences.edit()
.putBoolean("example", true)
.apply()

Any ideas why it's happening?
Any ideas how to resolve/prevent the warning without saving this operation in a variable unnecessarily?

CodePudding user response:

Looks like a lint bug to me.

There is a handy edit extension function that lets you make your updates in a lambda and it automatically applies the change. More concise, and it will avoid this lint warning:

sharedPreferences.edit {
    putBoolean("example", true)
}

You will need the androidx.core:core-ktx library in your dependencies if you don't already have it.

  • Related