Data Binding in Android: Getting Started

In this Android Data Binding tutorial, you’ll learn how to link UI components to data in your app using a declarative format. By Evana Margain Puig.

4.9 (21) · 1 Review

Download materials
Save for later
Share

Linking code files with user interfaces is one of the most common tasks an Android developer faces. As simple as it sounds, this process causes many runtime errors and consumes a lot of time. Wouldn’t it be great if there was a library that took care of that?

The Data Binding Library is here to the rescue! Android introduced this library as part of the Jetpack suite of libraries at Google I/O 2018.

Data binding lets you handle the communication between views and data sources reliably and simply. Following this pattern is critical for many important architectures in Android development, particularly MVVM, currently one of the most used Android architectures.

In this tutorial, you’ll build GoBuy, a shopping list app, to learn how to integrate the Data Binding Library into existing Android projects. Along the way, you’ll learn:

  • How to enable data binding in your project
  • How to convert an existing layout file to one that works with data binding
  • How to work with code generated by the Data Binding Library in your Activities and Fragments
  • How to use data binding in RecyclerView and ViewHolder
Note: This tutorial assumes you know the basics of Android development with Kotlin. If you’re new to Kotlin, check out this Kotlin introduction tutorial. If you’re completely new to Android development, read through this Beginning Android Development tutorial to familiarize yourself with the basics.

Getting Started

Download the starter project by clicking the Download Materials button at the top or bottom of the tutorial and unzip it. Extract both begin and end folders from the zip file. Open the begin project by selecting Import project (Gradle, Eclipse ADT, etc) from the welcome screen of Android Studio 3.5 or later.

Wait for the Gradle sync to finish. Look at the project structure.

List of files including model, view and viewmodel for the project app, GoBuy.

As you can see in the screenshot above, the folder structure follows the MVVM architecture. There’s a file for the Model, another for the View and one for the ViewModel. During this tutorial, you’ll work with the files in the View folder, as well as the layout XML files in resources/layout, as shown in the screenshot below.

List of app layout files including activity grocery list, dialog and list item. .

Build and run. You’ll see the initial version of your shopping list.

Empty GoBuy screen with button to add items.

The app is functional and easy to navigate. Try adding a product by clicking the Add item button at the top-left corner of the screen. Fill in the dialog that appears and click the Save button. The item appears in the list with an option to edit or delete it.

Dialog for adding items asking for name, amount and price

Say you want to make sandwiches for your friends. You need to buy one loaf of bread, one jar of jam, two packages of cheese and a jar of mayonnaise. Add these to your shopping list.

List screen with bread, cheese, jam and mayonnaise.

Did you get a result similar to the screenshot above? Try playing with different values until you feel comfortable navigating through the app.

Before you dive into the project, it’s important to learn a little more about data binding.

Why Use Data Binding

Every developer wants clean and understandable code, but creating it is easier said than done. People rush, releases come one after another, clients want results and before you know it, your code is a mess.

Knowing this, the Android team decided to make things easier by standardizing development. To that end, they launched the Jetpack libraries, which include the Data Binding Library. This library offers several advantages:

  1. Less code: By keeping code in activities and fragments small, it helps you write cleaner and more readable code.
  2. Fewer errors: The binding is checked at compile time.
  3. Faster apps: Since the binding isn’t done in onCreate, your app runs faster.
  4. Safer connection between views and code: Because it doesn’t bind at runtime, it’s safer to get the UI components than findViewById().
  5. Safer connection between views and action: Data binding is safer than relying on onClick(), which can crash if you didn’t implement the requested method.
  6. Easier: Since it has less code and causes fewer errors, it’s easier to test and maintain.

Now that you understand the benefits, it’s time to discuss how data binding works.

How Data Binding Works

Data binding is about connecting views in the XML layout with data objects: In this case, Kotlin code. The Data Binding Library generates the classes needed for this process.

Layout XML files that use data binding are different because they start with a root layout tag followed by a data element and a view root element. This view root element is what your root would be in a non-binding layout file.

Each layout file then has its own generated data binding class. The Jetpack library does the job for you. By default, the class name is the name of the layout file in Pascal case and with the word binding at the end.

For example, in this project, activity_grocery_list.xml has the binding class ActivityGroceryListBinding.

Data binding has three main uses:

  • Showing data.
  • Handling user events.
  • Invoking actions on layout variables.

With that in mind, it’s time to prepare the project for data binding.

Configuring for Data Binding

First, you’ll configure the project for data binding. Open the build.gradle from the app directory. Locate the TODO comment at the bottom of this file and add the following code there:

dataBinding {
  enabled true
}

This tells Gradle that you want to build your project with the Data Binding Library.

Build and run. You’ll see the same screen you did in the beginning.

List screen with only bread listed.

Next, you’ll convert an existing XML layout to work with data binding.

Transforming a Standard XML Layout Into a Data Binding Layout

To convert a regular XML layout file to data binding layout, you need to follow three simple steps:

  1. Wrap your layout with a layout tag.
  2. Add layout variables (optional).
  3. Add layout expressions (optional).

You’ll repeat step one in each of the three XML layouts in the project. Start by opening activity_grocery_list.xml. You’ll find a TODO at the top of this file.

<layout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools">
 <data>
 </data>

You need to close this tag at the very bottom of the file. So, go to line 63, add a new line and close it with the following code:

</layout>

With this code added, this layout can use data binding. Otherwise, it would be a standard layout file and generate the automatic binding files.