Fixing NullPointerException when trying to bind RatingBar rating value
Android Data Binding Library is useful but sometimes you have some problems with it… this post is about one of them.
My most recent problem was with including a layout that passes a Data Object to the included layout, just like this
<!-- parent_layout.xml -->
<!-- a lot of stuff -->
<!-- included_layout.xml -->
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 :(
Fortunately with Data Binding library is possible to define custom setters.
And in your layout changes the RatingBar code to:
Keep coding! :)