I have following code that produces following lint error.
fun newInstance(message: String?): DialogFragment {
return DialogFragment().apply {
arguments = Bundle().apply {
putString("arg", message)
}
}
}
The message points out that this
reference inside apply()
function points to BaseBundle
class that is available since API 21 which will crash on lower API. Bundle#putString(key, value) is definitely available on lower versions, but there is an error in Android Studio 3.0-alpha8.
The issue quite strange as I can see decompiled code as this:
Which do reference Bundle
type not a BaseBundle
.
Why do we have Lint error in first place?
It really looks like a bug It is a known bug but one could actually see why you're getting the warning if looking at Bundle.java source code.
Before api 21 Bundle
had a method (check here)
public void putString(@Nullable String key, @Nullable String value)
and the class itself had no super class. From api 21 Bundle
extends a newly added BaseBundle
class and this method putString
had been moved to BaseBundle
. So, when you call the method on api 21 and above, the method belongs to BaseBundle
, for lower version it belongs to Bundle
.
This is somehow related to the apply
block because the warning doesn't appear if you call the method on a Bundle
-type variable directly.
One workaround is to use let
instead of apply
, like:
fun newInstance(message: String?): DialogFragment {
return DialogFragment().apply {
arguments = Bundle().let {
it.putString("arg", message)
it
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With