Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java
  • Android
  • Kotlin
  • Flutter
  • Dart
  • Android with Java
  • Android Studio
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
Data Binding with ViewModel in Android
Next article icon

Data Binding with ViewModel in Android

Last Updated : 30 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Data Binding with ViewModel in Android

A

ayushpandey3july
Improve
Article Tags :
  • Kotlin
  • Android
  • Kotlin Android
  • Android-Misc

Similar Reads

    Data Binding with LiveData in Android
    Data Binding is a feature which help us to bind UI components with data sources in an Android application using a declarative format. 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 us
    3 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, Vie
    5 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.Step by Step Implementation:Step 1: Create a New ProjectIf you don’t know how to create a new project in
    2 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
    4 min read
    View Binding in Android Jetpack
    View Binding is one of the best features in Android that allows views to bind seamlessly with an ongoing activity. It replaces the traditional findViewById()method, significantly reducing boilerplate code by automatically generating instances of views for the current layout. One of its most importan
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences