Posted on

Rest (API) with Android Data Binding

Android Rest api with data binding

Hey guys, in previous post we looked at the basics of Android Data Binding and how to write less with it. Yes, Data Binding, amazing, you save time, no need to write bunch of boiler plate Java code. All sounds great in theory, but we don’t apply it. Especially on demo apps where Data Binding only ads extra overhead, does not save you time. After that experience you think, yes, great, but.. All because of old habits.  It’s easier to stick with them. But today I will show how much you will benefit from Data Binding on a real project.

The app which we will be working on today is going to display list of latest movies and show details activity for each. As you can tell from the title, it’s gonna be a real data. And api which we’ll use is TMDB, which you might be familiar with if you taken Udacity Android developer nanodegree. We’ll use Retrofit library for fetching data. And Data Binding Library for setting data, let’s try do the whole thing in XML only. Not the whole app, of course, only setting data!

That’s the result I got

Android Rest with Data Binding

Set data

There’s almost no Java code required to set data on views. There’s a Movie model with 6 fields, which is Parcelable to be able to pass it to Details Activity. As you would guess the most logic goes to XML. In main activity there’s a RecyclerView with GridLayoutManager. All we need in here is add data tag to list_item.xml and use my custom imageUrl attribute from databinding-aux library to load the image with Glide.


Details activity layout



I fetch data from TMDB using Retrofit and it returns movie list


That’s the perfect use case for Data Binding, you receive ready model and provide it to layout. But actually there’s even a bigger advantage of using Data Binding, because it’s more natural. Yes, we all got used to switch between layout/Java. You create layout, switch to Java to update setting code or just keep layout in mind when writing Java, which gives an extra cognitive load. Now when you use Data Binding you just focus on layout, no need to go to Java code and back, you write layout, when you done you go to Java and won’t have to go back to layout unless you want to change it. You create views, check design and set data right there. You can even set listeners there. If you don’t know how to create custom listeners or attributes you can check this blog post. And then you just go to Java class and add one line – setModel().


You should really try building it yourself and feel the process.