Observable Data Object refers to the capability of an object to notify others about the changes in Its data and the data binding library allows us to make objects observable. Let’s understand with the help of example what I’m talking about.
In the previous article, I have explained about data binding concept with the help of a demo. I will move forward with that demo. The previous article is here Data Binding in Android Tutorial
Working App of Observable Data Object (Sample App)
Implement BaseObservable in Data Model class
The Data Binding library provides the BaseObservable class which implements the listener registration mechanism. Now User class (from the previous demo) inherit from BaseObservable. It will be responsible for notifying when its properties changes. So to do that we will use the @Bindable annotation. To make User class Observable Let’s extended the BaseObservable class.
package com.wave.databindingexample;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
/**
* Created on : Mar 16, 2019
* Author : AndroidWave
*/
public class User extends BaseObservable {
private String name;
private String address;
private String followerCount;
private String followingCount;
public User(String name, String address, String followerCount, String followingCount) {
this.name = name;
this.address = address;
this.followerCount = followerCount;
this.followingCount = followingCount;
}
@Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
@Bindable
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
notifyPropertyChanged(BR.address);
}
public String getFollowerCount() {
return followerCount;
}
public void setFollowerCount(String followerCount) {
this.followerCount = followerCount;
}
public String getFollowingCount() {
return followingCount;
}
public void setFollowingCount(String followingCount) {
this.followingCount = followingCount;
}
}
I have bind getter properties using @Bindable annotation and for setter properties, we used notifyPropertyChanged() methods which will observe the changes in name variables and address variables. They notify about any changes in it. You see I have using BR class in notifyPropertyChanged() methods. This is a class that autogenerate by data binding which contains ids of the resources used for data binding. generatedJava=>com=>wave.databindingexample(this is package name in our case) you can find here BR.java. Here we have all the resource which are used for data binding.
Add two EditText in layout file
After all, this opens the activity_main.xml. I have to make a few changes in the previous layout. Let’s add two EditText one for name that id is etName and second for address like etAddress. Now set the text using bindable object variable like android:text=”@={user.name}”
We do not need any changes to MainActivity. Now the changes in android:text=”@={user.name}” this name will be observed and it will notify TextView.
Conclusion
Now let us see how it works. Just run the application, the application is up and running. So we have made name and address is observable so any change in name and address you can see the TextView automatically changes.
Download Sample Project- Observable Data Object using Data Binding
Data Binding library helps us to bind the observable data to the UI elements and tell you everything about it in this article, and will implemented in a demo application as well.
What is Data Binding
It is a part of android architecture components. Today data binding is a hot buzzword Android developers quite recently. It is a support library that allows us to bind the UI components in the layout to data resources and this is done in a declaration format rather than doing it programmatically. So it reduces the boilerplate code a lot.
It helps us to keep the code very organised since it has a definite project architecture structure. With the help of Data Binding the no more need offindViewById(). It offers flexibility and compatibility and It is supported API level 14 or higher. Mean you can use it with devices Running Android 4.0 ( level 14 or higher).
Data Binding in Android Sample App
Data Binding Sample Application
Let’s move to Android studio and start getting our hands dirty with data binding. Go to file menu and create a new project with default template.
Now to enable data Binding in our Android project the first thing we need to make sure that we have support repository in the Android SDK manager.
To ensure you have to go tools => SDK manager => switch to tab SDK tools and make sure you have Android support repository if you don’t check the checkbox and hit apply. such as below snapshot
support repository
Configure your app to use the data binding
Open the app/build.gradle, Then you have to add these line of code inside the android tags in gradle and sync project
We use data binding expression for connecting to layout with data resource file. In this demo, We are taking the example of user profile screen. So we will understand the core working of data binding. Open the layout (XML) file activity_main and replace the root with layout tag and place all tags inside to layout tags.
Here is the layout tag tells the Android Framework that this activity main.xml then uses data binding of binding class is automatically generated for each layout file by the father name(Our case is MainActivity) of the class is based on the name of the layout file and added the Binding suffix. That means the name of auto-generated file is (for activity_main.xml ) MainActivityBinding.
Generated file name is => ActivityName in Capital Latter + Binding suffix
In case file is not generate rebuild the project. still doesn’t work go to files invalidate cache and restart
2. Replace the traditional setContentView() to DataBindingUtil.setContentView() in Activity
Open the MainActivity, create a object of DataBindingUtils class and replace the traditional setContentView() to DataBindingUtil.setContentView() like this
Now run the project and see, So here is our app up and running. now you able to set layout using data binding.
Let’s us see how to data bind with Views and Widget using data binding
Now we will bind view using data binding into our MainActivity. Mean we will access all views in our Activity using binding instance. Let’s see the below code
binding.tvName.setText("Monika Sharma");
binding.tvAddress.setText("251 mansarovar Jaipur | India ");
binding.tvFollowers.setText("240K");
binding.tvfollowing.setText("324K");
Now run the application. You will see the data have been changed as your expectations. The conclusion is we have successfully use the data binding instance to populate to widget in UI.
Bind the data object with Views
Let’s see how can we bind the data objects with views. To do that in the App java go src and create a class named is User.java which will be a data class. In that class create some properties such as name, address, followings and followers.
package com.wave.databindingexample;
/**
* Created on : Mar 16, 2019
*/
public class User {
private String name;
private String address;
private String followerCount;
private String followingCount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getFollowerCount() {
return followerCount;
}
public void setFollowerCount(String followerCount) {
this.followerCount = followerCount;
}
public String getFollowingCount() {
return followingCount;
}
public void setFollowingCount(String followingCount) {
this.followingCount = followingCount;
}
}
Declare data tag in activity_main.xml
Now move to the activity_main.xml, You have to make some changes in XML. We will use <data/> tag to define a variable inside the <layout> which is used the user data object. So variable name I keep it as user and data object type is User. Meanwhile, you have to set data to TextView using this user data object like this.
Now run the application and check if it works fine. So here again our app up and run. You have seen the update data that comes from the data object which we have defined in our layout file.
Event handling using Data Binding
Now let us consider some event handling using data binding. For to do create a new class named EventHandler and expose onButtonClick()
package com.wave.databindingexample;
import android.content.Context;
import android.widget.Toast;
/**
* Created on : Mar 16, 2019
* Author : AndroidWave
*/
public class EventHandler {
Context mContext;
public EventHandler(Context mContext) {
this.mContext = mContext;
}
public void onButtonClick(String name) {
Toast.makeText(mContext, "Now you are following " + name, Toast.LENGTH_SHORT).show();
}
}
Meanwhile, make I have made few changes in our layout file. I have added a follow button in the activity layout and define the variable to the event handler. After that set the button onClick functions like => android:onClick=”@{() -> handler.onButtonClick(user.name)}” . Finally, the layout xml looks like this
So we are all set with using the handler for the button click in our app. Now let’s run it and check how it works. So now click on the button and on clicking this we are getting the toast message. So way you can use data binding for event handling. In this article, we learned about layout binding and expression with event handling.
I the next article, I going to explain Working with Observable Data Object using Data Binding. I’m new in Android if you have any queries and suggestions put the comment in the comment box.