data binding - safeUnbox warning
I had the same warning, in my case changing the variable declaration from Boolean type to boolean type solve the problem:
From:
<variable name="readOnly" type="Boolean" />
To:
<variable name="readOnly" type="boolean" />
So, maybe you can try with:
<variable name="selectMap" type="android.databinding.ObservableMap<Integer, boolean>" />
You can add safeUnbox like this:
android:text="@{Double.toString(safeUnbox(product.listPrice))}"
w: warning: enabled is a boxed field but needs to be un-boxed to execute android:checked.
This warning comes because enabled field can be null. If you take Boolean
instead of boolean
, so Boolean
can be null. So this warning comes. That this field can make NullPointerException
.
---------------- Case 1 - One Way Binding----------------
<variable name="enabled" type="Boolean"/>....<Switch android:checked="@{enabled}" />
Solution 1
<Switch android:checked="@{safeUnbox(fieldName)}" />
Solution 2
Change Boolean
to primitive type boolean
. So that it never be null, default value of boolean
is false
.
<variable name="enabled" type="boolean"/>
---------------- Case 2 - Two-Way Binding----------------When you have two-way binding, then you can not use safeUnbox()
way, because safeUnbox()
will not be inverted.
<variable name="enabled" type="Boolean"/>....<Switch android:checked="@={enabled}" />
This will not work now.
<Switch android:checked="@{safeUnbox(fieldName)}" />
Solution 1
Change Boolean
to primitive type boolean
. So that it never be null, default value of boolean
is false.
<variable name="enabled" type="boolean"/>
Solution 2
A long way is to make inverse binding adapters for safeUnbox. See here.
What is safeUnbox() method?
safeUnbox()
just check null value and return non-null value. You can see below methods which are defined in Data binding library.
public static int safeUnbox(java.lang.Integer boxed) { return boxed == null ? 0 : (int)boxed;}public static long safeUnbox(java.lang.Long boxed) { return boxed == null ? 0L : (long)boxed;}public static short safeUnbox(java.lang.Short boxed) { return boxed == null ? 0 : (short)boxed;}public static byte safeUnbox(java.lang.Byte boxed) { return boxed == null ? 0 : (byte)boxed;}public static char safeUnbox(java.lang.Character boxed) { return boxed == null ? '\u0000' : (char)boxed;}public static double safeUnbox(java.lang.Double boxed) { return boxed == null ? 0.0 : (double)boxed;}public static float safeUnbox(java.lang.Float boxed) { return boxed == null ? 0f : (float)boxed;}public static boolean safeUnbox(java.lang.Boolean boxed) { return boxed == null ? false : (boolean)boxed;}