Android Data Binding

Filed Under: Android

With the introduction of Android M, one big change that’s come slightly less noticed is the introduction of Android Data Binding library. In this tutorial we’ll look into it’s need and implement it in our application.

Android Data Binding Overview

How many times have you seen that the activities/fragments code has numerous similar lines that just hookup the code with the XML markup? Unanimously, it’s the most boring work for a developer to do. Besides, it comes up with it’s own set of problems such as readability issues, increased time in debugging and having to keep a close eye on the annoying boilerplate code that can give rise to mistakes.

Thanks to the ButterKnife Library we’re able to use Annotations that reduces significant lines of code. But it still requires us to use @BindView or @InjectView and use findViewById for each view manually one by one.

The introduction of DataBinding Library with Android M is a blessing in disguise. It gives us the freedom to minimize the code for app logic that’s binding to the view. The DataBinding Library comes up with a mechanism where it auto generates the field names in our code from the respective view IDs. We’ll look into it shortly. First let’s jump onto the integration aspect.

Android Data Binding Integration

To integrate DataBinding make sure your gradle build bool version is 1.5 or above


dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
    }

To enable data binding, add the following code in the app module’s build.gradle.


android {
    ...
    dataBinding {
        enabled = true
    }
}

Syncing the Gradle makes Data Binding available for our project. Let’s proceed onto it’s implementation.

Android Data Binding Project Structure

We’ll use an empty Android Studio project for our implementation as shown below.

android-data-binding-project

The Layout

The earlier activity_main.xml layout we used to create looked like this:


<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.journaldev.databinding.MainActivity"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/tvHeading"
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content"
        android:text="JournalDev.com" />


    <TextView
        android:id="@+id/tvSubHeading"
        android:layout_width="wrap_content"
        android:layout_below="@+id/tvHeading"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content"
        android:text="Android Tutorials" />
</RelativeLayout>

To use Data Binding we need to add a layout as the root tag.

We’ve modified the activity_main.xml layout to include the layout tags as shown below.


<layout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.journaldev.databinding.MainActivity">

    <TextView
        android:id="@+id/tvHeading"
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content"
        android:text="JournalDev.com" />


    <TextView
        android:id="@+id/tvSubHeading"
        android:layout_width="wrap_content"
        android:layout_below="@+id/tvHeading"
        android:layout_centerHorizontal="true"
        android:layout_height="wrap_content"
        android:text="Android Tutorials" />
</RelativeLayout>
</layout>

Note: You need to build your project once now so that the auto-generated field names from the layout are available in the MainActivity.java

Code

We’ll replace the default MainActivity.java with the following one to bring DataBinding into use.



package com.journaldev.databinding;

import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.journaldev.databinding.databinding.ActivityMainBinding;


public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        binding.tvHeading.setText("Welcome to JournalDev.com");
        binding.tvSubheading.setText("Welcome to this Android Tutorial on DataBinding");
    }
}

Few new things to note in the above code are:

  • The ActivityMainBinding class is generated from the xml layout file and it’s named this way because the xml layout file name is turned into Upper CamelCase and appended with Binding
  • We’re invoking the xml layout in the setContentView (this is a static method) by calling
    
    DataBindingUtil.setContentView(this, R.layout.activity_main)
    
  • The IDs of the views of the xml layout get converted into camelCase field names too as it’s seen in the code above. As you can see it’s so easy to change the texts of the TextView widgets now

Note: If the ActivityMainBinding is not available even after building the project, try restarting Android Studio. It maybe because of the cache.

Few interesting Case Scenarios:

In the present layout we’ve defined the IDs in camelCase. What happens if you assign the same id as
android:id=”@+id/tv_Heading”?
Data Binding converts it into camelCase too and the field name remains the same.

What happens when the two IDs are like
android:id=”@+id/tvHeading” and android:id=”@+id/tv_Heading”?

Ideally DataBinding is smart enough and should convert the android:id=”@+id/tv_Heading” into tvHeading1 field name. But there is no surety. Also it can lead to confusion in tracking the field names with their respective IDs. Hence it’s recommended to stay with one type of naming convention. Ideally camelCase.

The output of the application is given below.

android data binding

This is just the power of DataBinding in the app code logic. There’s much more to it than this. We’ll look at them in later tutorials. You can download the final Android DataBinding Project from the link below.

Comments

  1. Wong S.H says:

    This is the simplest example of data binding I have ever found in the web. Well done and thank you very much.

  2. Nevil says:

    great job !
    can you help pls.
    pls can you send your email address to send my xml file and java file .thanks

    Dear friend I’m new to write apps and using android studio. So i’m expecting your valuable suport to get follwing output . Thanks inadvance
    I have no idea to give second input

    there are 2 inputs which one input coming through the progamatically and other one is a user input
    there is no problem about progamatically input ,I have written aprogram to get input
    I have problem how to give user input toget desire output as follows in android studio

    The data array is as follows. Groups may be added than shown.
    group child
    0 cricket india s.africa australia
    1 football brazil russia england
    2 athletic usa japan china
    3 vollyball srilanka nepal germany

    as example
    say sombody selected own country as “japan” manually (it includes athletic group)
    at this moment the child set of database (whole 3country set- not only the single item) should circulate as follows ie. The selected country group comes to top but group name never change
    group child
    0 cricket usa japan china
    1 football srilanka nepal germany
    2 athletic india s.africa australia
    3 vollyball brazil russia england

    always circulates 3 childs as one set

    say he inputs number 4 then programe gives “srilanka” (this is the program given input)
    the database may rearranged as follows
    group child
    0 cricket srilanka nepal germany
    1 football india s.africa australia
    2 athletic brazil russia england
    3 vollyball usa japan china

    1st output- Own to desire is “football”
    2nd output- desire to own is “vollyball”

    the 1st output gives after counting japan group “cricket ” to srilanka group “football”)
    the 2nd output gives after counting srilanka group “cricket to japan group “vollyball”)

  3. Angel says:

    To be honest you have wonderful easy to understand and very usefull resources lightweight and working examples, thank you Anupam!

  4. Muhammad Zawawi Bin Manja says:

    always helpful this blog..thank you again anupam..i like how you provide the source code. Already try a lot other website but no source code. Eventhough some have source code , it will not run. So frustrated. Your blog already is in my book mark

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content