I'm trying to use the null coalescing operator in my data binding. I have a compound drawable that I need to show one of three drawable icons, depending on if the variable is null, true, or false.
The XML
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="android.view.View" />
<variable
name="dataModel"
type="com.my.app.MyDataModel" />
</data>
<TextView
android:id="@id/mCompoundDrawable"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="@{(dataModel.isSelected ? @drawable/selected : @drawable/not_selected) ?? @drawable/not_specified }"
android:focusable="true"
android:gravity="center_vertical"
android:scrollHorizontally="false"
android:text="@{dataModel.text}" />
</layout>
The Data Model
public class MyDataModel
{
public String text;
public Boolean isSelected;
public MyDataModel(String text, Boolean isSelected)
{
this.text = text;
this.isSelected = isSelected;
}
}
I invoke this by calling:
MyDataModel dataModel = new MyDataModel(text, null);
binding.setDataModel(dataModel);
I thought that
android:drawableRight="@{(dataModel.isSelected ? @drawable/selected : @drawable/not_selected) ?? @drawable/not_specified }
is effectively the same as:
android:drawableRight="@{dataModel.isSelected != null? (dataModel.isSelected ? @drawable/selected : @drawable/not_selected) : @drawable/not_specified }
However, I get the following exception at runtime:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
I'm wondering how I can overcome this error. Thanks!