dcsimg
December 7, 2016
Hot Topics:

How to Use Android Data Binding

  • March 14, 2016
  • By Vipul Patel
  • Send Email »
  • More Articles »

Introduction

Most applications typically work with data. Until recently, Android developers had to write a lot of code because of no first-class platform support for data binding.

Developers need to get the data for a database or user input and then assign values to the elements that present it to the user in the UI. This made Android data binding a pretty laborious, non-intellectual exercise for developers.

Data Binding Basics

Traditionally, data binding involved inflating XML layout in the activity, finding the element in the layout by using a method such as findViewbyID, assigning the element to a local variable, getting value from the data, and, finally, assigning value to an element property.

We need to repeat this for each element in the layout that involves data. That is a lot of code that is repeated, and gets in the way of writing core application logic. All this is required to support data binding because there is no first-class support.

In Google IO 2015, a new data binding library was demonstrated; it removes the need to write such code. This library helps change the data binding development into the following three steps:

  • Create a binding from a layout
  • Retrieve the data
  • Bind the data to the view

This reduction in code authoring is powered by code that is generated by the data binding library that analyzes the layout file. The Gradle plugin then creates a binding class file and then creates binding methods in the class file.

To use data the binding library, you will need to use a newer version of Android Studio and associated build tools. We also need to update the Android Plugin for Gradle to version 1.3 or later, and add the latest Data Binding plugin. You can get these by installing or updating the Android Support Repository and Android Support library to the latest version.

Let us create a simple application to illustrate data binding.

Hands On

Fire up Android Studio and Start a new Android Studio Project.

Bind1
Figure 1: Starting a new Android Studio Project

Provide DataBindingDemo as the Application Name and click Next.

Bind2
Figure 2: Naming the application

On the next screen, leave the default values and click Next.

Bind3
Figure 3: Leaving the default values in place

On the "Add an activity to Mobile" page, choose "Blank Activity". This creates an application with a single activity.

Bind4
Figure 4: Adding a Blank Activity

We then are prompted to customize the activity. We will leave the default values unchanged.

Bind5
Figure 5: Again, leaving the default values in place

Click Finish to creating the project files.

The first thing we will do is to verify that the Gradle dependencies are correct.

Open build.gradle (Project:DataBindingDemo) and verify the classpath dependencies.

Bind6
Figure 6: Opening build.gradle to verify the classpath dependencies

In our case, we should see the following:

// Top-level build file where you can add configuration options
// common to all sub-projects/modules.

buildscript {
   repositories {
      jcenter()
   }
   dependencies {
      classpath 'com.android.tools.build:gradle:1.5.0'

      // NOTE: Do not place your application dependencies here;
      // they belong in the individual module build.gradle files
   }
}

allprojects {
   repositories {
      jcenter()
   }
}

If you are upgrading an older project, you would want to ensure that the Gradle library version is updated to atleast 1.5.0.

Next, we open the Gradle file for our app (build.gradle Module:app).

Bind7
Figure 7: Opening the Gradle file

The default content is as shown here:

apply plugin: 'com.android.application'

android {
   compileSdkVersion 23
   buildToolsVersion "23.0.2"

   defaultConfig {
      applicationId "com.example.vipul.databindingdemo"
      minSdkVersion 15
      targetSdkVersion 23
      versionCode 1
      versionName "1.0"
   }
   buildTypes {
      release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android.txt'),
         'proguard-rules.pro'
      }
   }
}

}

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   compile 'com.android.support:appcompat-v7:23.1.1'
}

We make the following changes.

apply plugin: 'com.android.application'

android {
   compileSdkVersion 23
   buildToolsVersion "23.0.2"
   defaultConfig {
      applicationId "com.example.vipul.databindingdemo"
      minSdkVersion 15
      targetSdkVersion 23
      versionCode 1
      versionName "1.0"
   }
   buildTypes {
      release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android.txt'),
         'proguard-rules.pro'
      }
   }
   dataBinding {
      enabled = true
   }


}

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   compile 'com.android.support:appcompat-v7:23.1.1'
}

We are now ready to use data binding.

Next, we will add a couple of textview controls on activity_Main. (We will also delete the default TextView - Hello World - that Android Studio creates).

The layout file will look as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity">

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="UnBound"
      android:id="@+id/textViewUnBound"
      android:layout_marginTop="72dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"/>

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="DataBound"
      android:id="@+id/textViewDataBound"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true"/>
</RelativeLayout>

Next, we will power one of the textviews without data using the data binding library and one with data.

Make the following changes. Add a new class to the project, called MyDataBindingHelper.

Bind8
Figure 8: Adding a new class

package com.example.vipul.databindingdemo;
/**
 * Created by vipul on 1/31/2016.
 */
public class MyDataBindingHelper {

   private String salutation;
   public static MyDataBindingHelper get(String salutation)
      {return new MyDataBindingHelper(salutation);}
   public MyDataBindingHelper(String salutation)
      {this.salutation = salutation;}
   public String getMessage()
      {return String.format("Hi %s", salutation);}
}

This is the helper class that will help with data binding the elements with data.

To use data binding library, we need the layout files to have the root tag of layout followed by a data element and a view root element.

The layout files will change as shown here:

<layout>
<data>
   <variable
      name="mydatabindinghelper"
      type="com.example.vipul.databindingdemo.MyDataBindingHelper"/>
</data>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity">

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="UnBound"
      android:id="@+id/textViewUnBound"
      android:layout_marginTop="72dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@{mydatabindinghelper.message}"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true"
      />
</LinearLayout>
</layout>

Next, we will make changes in the onCreate method: we will show both methods, one without using data binding library and one with.

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   // Line 1
   TextView unbound = (TextView)
      findViewById(R.id.textViewUnBound);
   // Line 2
   MyDataBindingHelper myDataBindingHelper =
      MyDataBindingHelper.get("Unbound");

   // Line 3
   unbound.setText(myDataBindingHelper.getMessage());


   // Line 4
   ActivityMainBinding binding =
      DataBindingUtil.setContentView(this, R.layout.activity_main);
   // Line 5
   binding.setMydatabindinghelper(MyDataBindingHelper.get("Bound"));
}

One can see from the preceding example the simplicity of the approach of using data binding library. For every additional control, we would have to write three lines (Lines 1-3) without using a data binding library, However, with a data binding library, we only have to write one line (Line 5) for each additional control. That is a much simpler developer experience.

We can see that Android Studio has done the heavy lifting by opening up activity_main from the intermediate files folder and checked out its contents.

On my computer, this file was located at C:\Users\vipul\AndroidStudioProjects\DataBindingDemo\app\build\intermediates\res\merged\debug\layout\activity_main.xml. Check out the copy of file on your system to see what magic Android Studio cooked up.

Summary

In this article, we learned about how to use a data binding library to make things simpler to hook up to data in Android applications. I hope you have found this information useful. You can download the sample code from here.

About the Author

Vipul Patel is a technology geek based in Seattle. He can be reached at vipul.patel@hotmail.com. You can visit his LinkedIn profile at https://www.linkedin.com/pub/vipul-patel/6/675/508.


Tags: XML, Android, library, android studio, Gradle, Android applications, data binding, Google IO 2015




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel