Last Updated: July 30, 2016

Android Data binding

Description: In this post I'm gonna illustrate concept of 'Data Binding' in android. So straight away.

Let's get started.



'DataBinding' in android was introduced as an effort to coupled the model i.e data directly into the view, thereby eliminating findViewById()  at much larger extend. Although its not limited to this and can help to remove lots of boilerplate code thereby. Its the direct roadway to implement MVVM pattern in our apps.

Prerequisite:

1. Add below snippets into your 'Modulebuild.gradle within 'android' section
    dataBinding {
        enabled true
       }

2. Now just add below line within the your 'Project'  build.gradle within 'dependencies' section.
Note: The gradle plugin should be greater or equals v1.5 +
 classpath 'com.android.tools.build:gradle:1.5.0 

Let's start with simple example of how to eliminate findViewById in activity.

1. Eliminate findViewById();

Step 1: Simply create a model with a field name as 'title' and also the POJO for the same.

public class SingleModel {

    private String title;

    public SingleModel() {
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

Step 2: In our activity_main.xml wrap your parent layout within '<layout> ...< /layout>' . As shown below. Create a <data> ...</data> tag with <variable>...</variable> to access its model variables

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

    <data>
        <variable
            name="single"
            type="com.code2concept.databinding.models.SingleModel"/>
    </data>

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@{single.getTitle()}"/>
    </RelativeLayout>
</layout>

Note: 1. Once you have created a variable into <layout> apt builds the binding file name BR.java(similar concept what R.java doeswhich and other binding functions.

Step 3: Lets integrate in our MainActivity. 

public class MainActivity extends AppCompatActivity {

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

        SingleModel singleModel = new SingleModel();
        singleModel.setTitle("Wow ! Data binding is awesome");
        mainActivity.setVariable(BR.single, singleModel);

    }
}

Bingo ! we have integrated databinding in our app







2. Handle click.

Step 1: Create a <variable> ... </variable> tag with name and type as shown below.

Note: Type can be created from separate class as well. We're gonna implement onClick in Activity.

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="single"
            type="com.code2concept.databinding.models.SingleModel"/>

        <variable
            name="singleClick"
            type="com.code2concept.databinding.MainActivity"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:onClick="@{singleClick.onClick}"
            android:text="@{single.getTitle()}"/>
    </RelativeLayout>
</layout>

    

Step 2: Finally bind the singleClick to the activity as shown below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

        SingleModel singleModel = new SingleModel();
        singleModel.setTitle("Wow ! Data binding is awesome");
        mainActivity.setVariable(com.code2concept.databinding.BR.single, singleModel);

        //bind click to the  activity
        mainActivity.setSingleClick(this);
    }

    @Override
    public void onClick(View view) {
        Toast.makeText(this, "Single Model view is clicked", Toast.LENGTH_SHORT).show();
    }
}

Great, we have handled onClick event as well

Question: what happens when the content of the view need to be changed in the runtime?.
No need to worry 'DataBinding' helps us effortlessly.






3. NotifyChangeProperty

Step1: Add @Bindable annotation to the getters and notifyPropertyChanged() to the setters as shown below.

public class SingleModel extends BaseObservable {

    private String title;


    @Bindable
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
        notifyPropertyChanged(BR.title);
    }
}

Step 2: Finally lets change our title on onClick. fig.1

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private SingleModel singleModel;
    private ActivityMainBinding mainActivity;

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

        singleModel = new SingleModel();
        singleModel.setTitle("Wow ! Data binding is awesome");
        mainActivity.setVariable(BR.singleModel, singleModel);

        //bind click to the  activity
        mainActivity.setSingleClick(this);
    }

    @Override
    public void onClick(View view) {
        singleModel.setTitle("Title is changes successfully");
    }
}

databinding
fig.1

Awesome, finally we have integrated databinding in our project ;-). Part 2 coming soon


37 comments :

  1. Moreover, in contrast to its partner, DA depends on the data which is as of now available to the scientist.data science course in pune

    ReplyDelete
  2. Thank you so much for helping me out to find the Data analytics course in Mumbai Organisations and introducing reputed stalwarts in the industry dealing with data analyzing & assorting it in a structured and precise manner. Keep up the good work. Looking forward to view more from you.

    ReplyDelete
  3. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
    data science

    ReplyDelete
  4. Such a very useful article. I have learn some new information.thanks for sharing.
    data scientist course in mumbai

    ReplyDelete
  5. Such a very useful article. I have learn some new information.thanks for sharing.
    data scientist course in mumbai

    ReplyDelete
  6. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.
    Data science course in mumbai

    ReplyDelete
  7. Such a very useful article. Very interesting to read this article. I have learn some new information.thanks for sharing. ExcelR

    ReplyDelete
  8. I am impressed by the information that you have on this blog. It shows how well you understand this subject.
    ExcelR Data Analytics courses

    ReplyDelete
  9. Very nice blog here and thanks for post it.. Keep blogging...
    ExcelR data science training

    ReplyDelete
  10. Attend The Analytics Training Institute From ExcelR. Practical Analytics Training Institute Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Analytics Training Institute.
    ExcelR Analytics Training Institute

    ReplyDelete
  11. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.
    ExcelR data science course in mumbai

    ReplyDelete
  12. I am impressed by the information that you have on this blog. It shows how well you understand this subject.
    data analytics courses

    ReplyDelete
  13. Nice information, valuable and excellent work, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here. data science course

    ReplyDelete




  14. Very Good Information...

    Data science Course in Pune


    Thank You Very Much For Sharing These Nice Tips..

    ReplyDelete
  15. Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also Admond Lee

    ReplyDelete
  16. I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. Admond Lee

    ReplyDelete
  17. A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one.I curious more interest in some of them hope you will give more information on this topics in your next articles.
    Data Science training in hyderabad

    ReplyDelete
  18. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    data analytics course
    business analytics course
    data science course

    ReplyDelete
  19. Attend The Business Analytics Course From ExcelR. Practical Business Analytics Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Course.
    ExcelR Business Analytics Course
    Data Science Interview Questions
    We are located at :
    Location 1:
    ExcelR - Data Science, Data Analytics Course Training in Bangalore
    49, 1st Cross, 27th Main BTM Layout stage 1 Behind Tata Motors Bengaluru, Karnataka 560068
    Phone: 096321 56744
    Hours: Sunday - Saturday 7AM - 11PM
    Location 2:
    ExcelR
    #49, Ground Floor, 27th Main, Near IQRA International School, opposite to WIF Hospital, 1st Stage, BTM Layout, Bengaluru, Karnataka 560068
    Phone: 070224 51093
    Hours: Sunday - Saturday 7AM - 10PM

    ReplyDelete
  20. keep up the good work. this is an Ossam post. This is to helpful, i have read here all post. i am impressed. thank you. this is our data analytics course in mumbai
    data analytics course in mumbai | https://www.excelr.com/data-analytics-certification-training-course-in-mumbai

    ReplyDelete
  21. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.

    digital marketing course

    ReplyDelete

  22. Nice post. Thanks for sharing! I want people to know just how good this information is in your blog. It’s interesting content and Great work.
    360DigiTMG digital marketing courses in hyderabad

    ReplyDelete
  23. keep up the good work. this is an Ossam post. This is to helpful, i have read here all post. i am impressed. thank you. this is our data analytics course mumbai
    data analytics course mumbai | https://www.excelr.com/data-analytics-certification-training-course-in-mumbai

    ReplyDelete
  24. keep up the good work. this is an Ossam post. This is to helpful, i have read here all post. i am impressed. thank you. this is our data science training in mumbai
    data science training in mumbai | https://www.excelr.com/data-science-course-training-in-mumbai

    ReplyDelete
  25. This is a wonderful article, Given so much info in it, Thanks for sharing. CodeGnan offers courses in new technologies and makes sure students understand the flow of work from each and every perspective in a Real-Time environmen python training in vijayawada. , data scince training in vijayawada . , java training in vijayawada. ,

    ReplyDelete
  26. It's late finding this act. At least, it's a thing to be familiar with that there are such events exist. I agree with your Blog and I will be back to inspect it more in the future so please keep up your act.

    business analytics course

    data analytics courses in mumbai

    data science interview questions

    data science course in mumbai

    ReplyDelete
  27. Impressive! I finally found a great post here. Nice article on data science . It's really a nice experience to read your post. Thanks for sharing your innovative ideas to our vision.
    Data Science Course in Marathahalli
    Data Science Course Training in Bangalore

    ReplyDelete
  28. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. anaconda install tensorflow

    ReplyDelete
  29. This is a fantastic website and I can not recommend you guys enough.
    data science course
    360DigiTMG

    ReplyDelete
  30. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.
    Know more Data Scientist Course

    ReplyDelete
  31. The information provided on the site is informative. Looking forward more such blogs. Thanks for sharing .
    Artificial Inteligence course in Faridabad
    AI Course in Faridabad

    ReplyDelete
  32. This Was An Amazing ! I Haven't Seen This Type of Blog Ever ! Thankyou For Sharing, data science courses

    ReplyDelete
  33. This Was An Amazing ! I Haven't Seen This Type of Blog Ever ! Thankyou For Sharing, data science training in Hyderabad

    ReplyDelete
  34. You might comment on the order system of the blog. You should chat it's splendid. Your blog audit would swell up your visitors. I was very pleased to find this site.I wanted to thank you for this great read!!
    data science courses in pune

    ReplyDelete

Your comments are valuable for us !!!