While studying android data-binding, my colleague told me that the android data-binding can be null in few cases, also when one layout includes another layout with data-binding, the generated data-binding file annotate the binding of another layout as @Nullable. My question is can data-binding be null and if yes when?
Finally, after so many years found an explaination for this. In case you are manually executing the DataBinding.inflate function then the returned DataBinding won't be null.
For auto generated bindings (i.e. when you include a layout and binding is generated and assigned to a variable in the parent layout binding), the data binding can be null based on some situation.
E.g.: Let's say we have layout as follow:
Portrait Mode layout: /src/res/layout/activity.xml
<LinearLayout ...>
<include
android:id="@+id/main_content"
layout="@layout/main_content_layout"
/>
</LinearLayout>
And for Lanscape mode: /src/res/layout-land/activity.xml
<LinearLayout ...>
<include
android:id="@+id/sidebar"
layout="@layout/sidebar_layout"
/>
<include
android:id="@+id/main_content"
layout="@layout/main_content_layout"
/>
</LinearLayout>
Now here as the multiple layout files are for same purpose but with different configuration (lanscape mode and portrait mode) the Android DataBinding will generate ActivityBinding.java file. Now here the developer would need to access binding for both sidebar and main content using object of ActivityBinding.java class. As the sidebar is not present in portrait mode layout file, the binding file won't have any reference. Hence the reference for sidebar binding would be kept as Nullable.
Hence, for the layout files with same name for different configuration and with different view hierarchy, the inner binding object generated can have null value, due to which the data binding may have Nullable binding fields.