Data Binding with ViewModel in Android - GeeksforGeeks

27 Sep, 2021
Prerequisite:
ViewModel
DataBinding
What is the benefit of integrating data binding in ViewModel? Simply we can say, It provides easy communication between VIEW and its data (or can say View’s Data). As we know the Views are defined in XML files and the XML file are linked with their activity or fragment file, but their data are stored in ViewModel objects. So if the data wants to communicate with the Views, the Activity or Fragment file will act as an intermediator. This will also increase the productivity of developers as it reduces boilerplate codes. So, In this article will we get to how to connect the Views and their Data directly which is there in ViewModel objects.
We will learn this by creating a simple app using Kotlin. 
Create an app with an empty activity. As we are using Data binding we need to enable Data Binding in build.gradle file
Create a ViewModel class
Kotlin
class MainViewModel : ViewModel() {    var text = " Welcome to my application "      fun updateText() {        text = " Text is Updated "    }}
Now we need to create a layout in XML and create a variable in the XML layout. Using data tag we declare a variable. 
XML
<?xml version="1.0" encoding="utf-8"?><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>        <variable            name="mainViewModel"            type="com.ayush.databinding.MainViewModel" />    </data>      <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:gravity="center"        android:orientation="vertical"        android:padding="50dp"        tools:context=".MainActivity">          <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center_vertical"            android:gravity="center_horizontal"            android:text="@{ mainViewModel.text }"            android:textSize="24sp" />          <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Update text"            android:onClick="@{ ()-> mainViewModel.updateText() }"/>      </LinearLayout>  </layout>
Now, we need to create a binding object in Activity, to pass the data to the variable which we defined in XML layout and MainViewModel object as a data source for the Views.
Kotlin
class MainActivity : AppCompatActivity() {      lateinit var binding: ActivityMainBinding    lateinit var mainViewModel: MainViewModel      override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)          mainViewModel = MainViewModel()          binding.mainViewModel = mainViewModel    }}
Output:
Our app is ready and it’s also working as we can see the data in form of text which was stored in the ViewModel object. So, we got to know how we directly communicate the View with its Data without taking the help of any intermediate. But, in this app, there is one issue as if we click the UPDATE TEXT button the text won’t be updated as expected, but it will remain the same. This is because we need to set the change text ( Data ) again to the View for any new data changes, so we need to define a function in the Activity file to Update the view. But we don’t want the communicate the View with Activity. 
So here we can use Live Data, Simply we can say, Live data is observer data holder class. If we declare any data as LiveData, then the data can be observed by Android components like Activity, Fragments, etc. Therefore, if we declare any data as Live Data and bind it using view binding to a View, then whenever the data changes the View gets automatically gets updated. In this article, we have discussed only Data binding with ViewModel and in the next article, we will also see Data Binding with LiveData.
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Kotlin Array
Android UI Layouts
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters