The Wayback Machine - https://web.archive.org/web/20240810153032/https://www.geeksforgeeks.org/data-binding-with-viewmodel-in-android/
Open In App

Data Binding with ViewModel in Android

Last Updated : 30 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

DataBinding is one of the most important concepts to really improve the performance of your Android Application It plays a vital role in the maintenance of the many Android Architectures. In this article, we will learn about DataBinding in ViewModel In Android.

Benefits of integrating Data binding in ViewModel

There are many benefits of using two important concepts of Android Application Development together as mentioned below:

  • It provides easy communication between VIEW and its data (or can say View’s Data).
  • Increase the productivity of developers as it reduces boilerplate codes: As we know the Views are defined in XML files and the XML files 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 intermediate.

So, In this article will we get to how to connect the Views and their Data directly which is there in ViewModel objects.

Step-Step for Data Binding with ViewModel in Android

We will learn this by creating a simple app using Kotlin. 

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Enable Data Binding in Application

Create an app with an empty activity. As we are using Data binding we need to enable Data Binding in the build.gradle file

gradle_module

Add a snippet to the build.gradle:

buildFeatures{
      dataBinding = true
}  

Step 3: Make Changes in the activity_main.xml file

activity_main.xml is one holding the layout of the whole application. Now we will be adding Data Binding to the Application by adding a layout tag to the activity_main.xml as mentioned below in the CodeBlock.

Here <data> tag can hold the layout variables and layout expressions that will assist us in the whole process.

< layout 
     // all namespaces 
     /> 
 
    <data>
            // layout variables/layout expressions
    </data>
 
     // Content of activity_main.xml

</layout>

Now we need to create a layout in XML and create a variable in the XML layout. Using a 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>


Step 4: Making Changes in the MainAcitivity.kt File

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.

Below is the MainAcitivity file with the changes to be added:

MainActivity.kt
// You need to add your package name here
package com.example.data_binding_viewgroup

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import com.example.data_binding_viewgroup.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
  
      // lateinit variables declared here used 
      // for binding and for storing the ViewModel to 
      // be updated
    lateinit var binding: ActivityMainBinding
    lateinit var mainViewModel:MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        
        // Storing the value of extracted in DataBinding
        binding = DataBindingUtil.setContentView(this,R.layout.activity_main)

        // Model stored in the variable
        mainViewModel = MainViewModel()

        // Data binding the ViewModel
        binding.mainViewModel = mainViewModel
    }
}


Create a ViewModel class

We want to add Changes in the View Groups all changes are mentioned in a MainViewModel Class which can be used while Data Binding. We Create MainViewModel.kt. by right-clicking and creating Kotlin Class/File name it as MainViewModel.kt.

Navigate to the New Created File:

View_Model_class

Add the changes mentioned below:

MainViewModel.kt
package com.example.data_binding_viewgroup
import androidx.lifecycle.ViewModel

class MainViewModel : ViewModel(){
    var text = "This is my Application"

    fun updateText(){
        text = "text is Updated"
    }
}


Output:

DataBinding_ViewGroup

Github Final Application:

The Final Application Created Can be downloaded from this link – GitHub Link for the Data Binding Android Application

Issues with this Application

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. 

Solution of the Problem:

So here we can use Live Data, Simply we can say, that Live Data is an 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.



Similar Reads

MVVM (Model View ViewModel) Architecture Pattern in Android
Developers always prefer clean and structured code for projects. Organizing the codes according to a design pattern helps in the maintenance of the software. By having knowledge of all crucial logic parts of the android application, it is easier to add and remove app features. Further, design patterns also assure that all the codes get covered in U
7 min read
ViewModel in Android Architecture Components
ViewModel is part of the android architecture component. Android architecture components are the components that are used to build robust, clean, and scalable apps. Android architecture components hold some classes to manage UI components and Data persistence. The ViewModel class is designed to store and manage UI-related data in a lifecycle-consci
5 min read
ViewModel With SavedState in Android
Google launched Android Jetpack at Google I/O 2018, which is a bundle of components, tools, and guidelines for creating excellent Android apps. It included LiveData, ViewModel, Room Database, Work Manager, and other components. ViewModel will be discussed in this blog. In the Activity lifecycle, ViewModel maintains UI-related data. It enables the A
5 min read
Unit Testing of ViewModel with Kotlin Coroutines and LiveData in Android
The official documentation says that coroutines are lightweight threads. By lightweight, it means that creating coroutines doesn’t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later. In this article, we will learn how to write a unit test for a Vie
4 min read
Assisted Dependency Injection in ViewModel with Dagger-Hilt in Android
If you use Dagger-Hilt Dependency Injection in your android project then you must have encountered a case where you want to manually supply some parameters to construct an object in order to inject it. Generally when we inject a dependency/object in a class then the Dagger-Hilt framework construct it behind the scenes by automatically passing speci
6 min read
Shared ViewModel in Android
In Android development, ViewModel serves as a means to facilitate data sharing among different fragments or activities. By utilizing the same ViewModel across multiple fragments, each fragment gains access to the shared data and functionality encapsulated within the ViewModel. This approach offers a streamlined method for enabling communication bet
5 min read
Fragment to Fragment Communication in Android using Shared ViewModel
If there are two or more fragments in an activity, they need to communicate and share the data between them. The traditional way of sharing the data between the two fragments is implementing the callback using an interface that is cumbersome and may throw exceptions. But the modern way of doing that is using shared ViewModel. So in this article, it
6 min read
Overview of Data Binding in Android Architecture Components
This article describes the idea behind the Data Binding and MVVM design pattern and its components. If you would like to experiment with it hands-on, open an old project with spaghetti code. If you don’t have one, you'll get one from GitHub. Then, attempt to use the MVVM components introduced during this article. In some ways, software development
4 min read
Data Binding with LiveData in Android
Prerequisite: DataBindingLiveData and ViewModel So, Why we are using Data binding with LiveData? Actually, If we want our views to directly communicate with ViewModel (Data source), we can do that simply without using LiveData. But if data changes in ViewModel it won't reflect its View. This is where we can take the help of LiveData, to automatical
2 min read
Data Binding in Android with Example
In Android, the Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. What we are going to build in this article?Here is a sample video of what we are going to build in this project. Note that we are going to make this proj
4 min read
Article Tags :
three90RightbarBannerImg