Fixing NullPointerException when trying to bind RatingBar rating value

Diego Y Kurisaki
1 min readAug 31, 2016

--

Android Data Binding Library is useful but sometimes you have some problems with it… this post is about one of them.

The Problem

My most recent problem was with including a layout that passes a Data Object to the included layout, just like this

<!-- parent_layout.xml -->
<layout>
<data>
<variable
name="dataObject" type=".Data"/>
</data>
<LinearLayout>
<!-- a lot of stuff -->
<include layout="@layout/included_layout"
app:dataObject="@{dataObject}"/>
</LinearLayout>
</layout>
<!-- included_layout.xml -->
<layout>
<data>
<variable
name="dataObject" type=".Data"/>
</data>
<LinearLayout>
<RatingBar android:rating="{@dataObject.rating}"/>
</LinearLayout>
</layout>

I was just trying to extract a layout containing a rating bar to another file, you know just so I don't have a layout with 1000 lines.

But when you do this you keep getting a NullPointerException because for some reason your layout is inflated and the bindings are executed before your Data object is set.
In the generated code something like this happens.

ratingBarView.setRating(rating); //rating == null :(

Fixing it

Fortunately with Data Binding library is possible to define custom setters.

And in your layout changes the RatingBar code to:

<RatingBar app:rating="@{dataObject.rating}"/>

That's it!
Keep coding! :)

--

--