The Wayback Machine - https://web.archive.org/web/20240930201105/https://www.geeksforgeeks.org/mvvm-model-view-viewmodel-architecture-pattern-in-android/
Open In App

MVVM (Model View ViewModel) Architecture Pattern in Android

Last Updated : 18 Oct, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 Unit Testing without the interference of other classes. 

Model — View — ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic(Views or UI) from the core business logic part of the application. 

The separate code layers of MVVM are:

  • Model: This layer is responsible for the abstraction of the data sources. Model and ViewModel work together to get and save the data.
  • View: The purpose of this layer is to inform the ViewModel about the user’s action. This layer observes the ViewModel and does not contain any kind of application logic.
  • ViewModel: It exposes those data streams which are relevant to the View. Moreover, it serves as a link between the Model and the View.

MVVM (Model View ViewModel) Architecture Pattern in Android

MVVM pattern has some similarities with the MVP(Model — View — Presenter) design pattern as the Presenter role is played by ViewModel. However, the drawbacks of the MVP pattern has been solved by MVVM in the following ways:

  1. ViewModel does not hold any kind of reference to the View.
  2. Many to-1 relationships exist between View and ViewModel.
  3. No triggering methods to update the View.

Ways to Implement MVVM in the Project

There are 2 ways to implement MVVM design pattern in Android projects:

  1. Using the DataBinding library released by Google
  2. Using any tool like RxJava for DataBinding.

Data Binding:

Google releases the Data Binding Library for Android that allows the developers to bind UI components in the XML layouts with the application’s data repositories. This helps in minimizing the code of core application logic that binds with View. Further, Two – way Data Binding is done for binding the objects to the XML layouts so that object and the layout both can send data to each other. This point can be visualized by the example of this tutorial.

Syntax for the two way data binding is @={variable}

Example of MVVM Architecture Pattern

Here is an example of a single activity User-Login android application to show the implementation of the MVVM architecture pattern on projects. The application will ask the user to input the Email ID and password. Based on the inputs received the ViewModel notifies the View what to show as a toast message. The ViewModel will not have a reference to the View. 

To enable DataBinding in the android application, following codes needs to be added in the app’s build.gradle(build.gradle (:app)) file:

Enable DataBinding:

android {

   dataBinding {

       enabled = true

      }

}

Add lifecycle dependency:

implementation ‘android.arch.lifecycle:extensions:1.1.1’

 

Below is the complete step-by-step implementation of the User-Login android application with MVVM pattern.

Step by Step Implementation

Note: Following steps are performed on Android Studio version 4.0

Step 1: Create a new project

  • Click on File, then New => New Project.
  • Choose Empty activity
  • Select language as Java/Kotlin
  • Select the minimum SDK as per your need.

Step 2: Modify String.xml file

All the strings which are used in the activity are listed in this file.

XML




<resources>
    <string name="app_name">GfG | MVVM Architecture</string>
    <string name="heading">MVVM Architecture Pattern</string>
    <string name="email_hint">Enter your Email ID</string>
    <string name="password_hint">Enter your password</string>
    <string name="button_text">Login</string>
</resources>


 
 

Step 3: Creating the Model class

 

Create a new class named Model to which will hold the Email ID and password entered by the user. Below is the code to implement the proper Model class.

 

Java




import androidx.annotation.Nullable;
 
public class Model {
 
    @Nullable
    String email,password;
 
    // constructor to initialize
    // the variables
    public Model(String email, String password){
        this.email = email;
        this.password = password;
    }
 
    // getter and setter methods
    // for email variable
    @Nullable
    public String getEmail() {
        return email;
    }
 
    public void setEmail(@Nullable String email) {
        this.email = email;
    }
 
    // getter and setter methods
    // for password variable
    @Nullable
    public String getPassword() {
        return password;
    }
 
    public void setPassword(@Nullable String password) {
        this.password = password;
    }
 
}


 
 

Step 4: Working with the activity_main.xml file

 

Open the activity_main.xml file and add 2 EditText to get inputs for Email and Password. One Login Button is also required to validate the user’s input and display appropriate Toast message. Below is the code for designing a proper activity layout.

 

Note: For the proper functioning of Data Binding Library, it is required to set the layout tag at the top. The constraint layout tag of XML will not work in this case.

 

XML




<?xml version="1.0" encoding="utf-8"?>
    xmlns:bind="http://schemas.android.com/tools">
 
    <!-- binding object of ViewModel to the XML layout -->
    <data>
        <variable
            name="viewModel"
            type="com.example.mvvmarchitecture.AppViewModel" />
    </data>
 
    <!-- Provided Linear layout for the activity components -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="8dp"
        android:background="#168BC34A"
        android:orientation="vertical">
 
        <!-- TextView for the heading of the activity -->
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/heading"
            android:textAlignment="center"
            android:textColor="@android:color/holo_green_dark"
            android:textSize="36sp"
            android:textStyle="bold" />
 
        <!-- EditText field for the Email -->
        <EditText
            android:id="@+id/inEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginTop="60dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="20dp"
            android:hint="@string/email_hint"
            android:inputType="textEmailAddress"
            android:padding="8dp"
            android:text="@={viewModel.userEmail}" />
 
        <!-- EditText field for the password -->
        <EditText
            android:id="@+id/inPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:hint="@string/password_hint"
            android:inputType="textPassword"
            android:padding="8dp"
            android:text="@={viewModel.userPassword}" />
 
        <!-- Login Button of the activity -->
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:layout_marginTop="60dp"
            android:layout_marginEnd="20dp"
            android:background="#4CAF50"
            android:fontFamily="@font/roboto"
            android:onClick="@{()-> viewModel.onButtonClicked()}"
            android:text="@string/button_text"
            android:textColor="@android:color/background_light"
            android:textSize="30sp"
            android:textStyle="bold"
            bind:toastMessage="@{viewModel.toastMessage}" />
 
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="135dp"
            app:srcCompat="@drawable/banner" />
 
    </LinearLayout>
</layout>


 
 

Step 5: Creating the ViewModel class

 

This class will contain all the methods which are needed to be called in the application layout. The ViewModel class will extend BaseObservable because it converts the data into streams and notifies the View when the toast message property will change.

 

Java




import android.text.TextUtils;
import android.util.Patterns;
import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
 
public class AppViewModel extends BaseObservable {
 
    // creating object of Model class
    private Model model;
 
    // string variables for
    // toast messages
    private String successMessage = "Login successful";
    private String errorMessage = "Email or Password is not valid";
 
    @Bindable
    // string variable for
    // toast message
    private String toastMessage = null;
 
    // getter and setter methods
    // for toast message
    public String getToastMessage() {
        return toastMessage;
    }
 
    private void setToastMessage(String toastMessage) {
        this.toastMessage = toastMessage;
        notifyPropertyChanged(BR.toastMessage);
    }
 
    // getter and setter methods
    // for email variable
    @Bindable
    public String getUserEmail() {
        return model.getEmail();
    }
 
    public void setUserEmail(String email) {
        model.setEmail(email);
        notifyPropertyChanged(BR.userEmail);
    }
 
    // getter and setter methods
    // for password variable
    @Bindable
    public String getUserPassword() {
        return model.getPassword();
    }
 
    public void setUserPassword(String password) {
        model.setPassword(password);
        notifyPropertyChanged(BR.userPassword);
    }
 
    // constructor of ViewModel class
    public AppViewModel() {
 
        // instantiating object of
        // model class
        model = new Model("","");
    }
 
    // actions to be performed
    // when user clicks
    // the LOGIN button
    public void onButtonClicked() {
        if (isValid())
            setToastMessage(successMessage);
        else
            setToastMessage(errorMessage);
    }
 
    // method to keep a check
    // that variable fields must
    // not be kept empty by user
    public boolean isValid() {
        return !TextUtils.isEmpty(getUserEmail()) && Patterns.EMAIL_ADDRESS.matcher(getUserEmail()).matches()
                && getUserPassword().length() > 5;
    }
}


 
 

Step 6: Define functionalities of View in the MainActivity file

 

The View class is responsible for updating the UI of the application. According to the changes in the toast message provided by ViewModel, the Binding Adapter would trigger the View layer. The setter of Toast message will notify the observer(View) about the changes in data. After that, View will take appropriate actions.

 

Java




import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.BindingAdapter;
import androidx.databinding.DataBindingUtil;
import com.example.mvvmarchitecture.databinding.ActivityMainBinding;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
 
        // ViewModel updates the Model
        // after observing changes in the View
 
        // model will also update the view
        // via the ViewModel
        ActivityMainBinding activityMainBinding
            = DataBindingUtil.setContentView(
                this, R.layout.activity_main);
        activityMainBinding.setViewModel(
            new AppViewModel());
        activityMainBinding.executePendingBindings();
    }
}
 
// any change in toastMessage attribute
// defined on the Button with bind prefix
// invokes this method
@BindingAdapter({ "toastMessage" })
public static void runMe(View view, String message)
{
  if (message != null)
    Toast
    .makeText(view.getContext(), message,
              Toast.LENGTH_SHORT)
    .show();
}


 
 

Output

Advantages of MVVM Architecture

  • Enhance the reusability of code.
  • All modules are independent which improves the testability of each layer.
  • Makes project files maintainable and easy to make changes.

Disadvantages of MVVM Architecture

  • This design pattern is not ideal for small projects.
  • If the data binding logic is too complex, the application debug will be a little harder.

 



Previous Article
Next Article

Similar Reads

Difference Between MVC, MVP and MVVM Architecture Pattern in Android
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in
6 min read
Difference Between MVC and MVVM Architecture Pattern in Android
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in
5 min read
Difference Between MVP and MVVM Architecture Pattern in Android
Developing an android application by applying a software architecture pattern is always preferred by developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in the
4 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
Android - Build a Movie App using Retrofit and MVVM Architecture with Kotlin
Model — View — ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic(Views or UI) from the core business logic part of the application. The separate code layers of MVVM are: Model: This layer is responsible for the a
5 min read
Build a Recipe App using MVVM Architecture with Kotlin in Android
In this article, we will make a recipe app that displays a list of Indian recipes using the retrofit library and MVVM architecture. Model — View — ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic(Views or UI) fr
7 min read
How to Build a Food and Their Price List Android App using MVVM Architecture with Kotlin?
In this article, we will food app that displays a list of foods and their price using the retrofit library and MVVM architecture. Model — View — ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic(Views or UI) from
5 min read
MVC (Model View Controller) Architecture Pattern in Android with Example
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in
8 min read
MVP (Model View Presenter) Architecture Pattern in Android with Example
In the initial stages of Android development, learners do write codes in such a manner that eventually creates a MainActivity class which contains all the implementation logic(real-world business logic) of the application. This approach of app development leads to Android activity gets closely coupled to both UI and the application data processing
12 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
Data Binding with ViewModel in Android
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 i
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
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
How to Build a Simple Note Android App using MVVM and Room Database?
Android provides us a feature with which we can store users' data inside their mobile itself with different storage options such as Shared Preferences, SQLite database, and the Room Database. All the data storing techniques are having different use cases. In this article, we will specifically take a look at using a Room Database with Architecture C
15+ min read
How to Build a Simple Contact List Android App using MVVM and Room Database?
A contact list app is a great tool to store and manage our contacts in one place. With the rise of smartphones and mobile devices, contact list apps have become increasingly popular. In this article, we will explore the development of a contact list app using Kotlin, Room Database, and MVVM architecture. Model — View — ViewModel (MVVM) is the indus
7 min read
How to Build a Grocery Android App using MVVM and Room Database?
In this article, we are going to build a grocery application in android using android studio. Many times we forget to purchase things that we want to buy, after all, we can’t remember all the items, so with the help of this app, you can note down your grocery items that you are going to purchase, by doing this you can’t forget any items that you wa
15+ min read
Difference Between MVC and MVP Architecture Pattern in Android
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in
3 min read
Android | Creating a Calendar View app
This article shows how to create an android application for displaying the Calendar using CalendarView. It also provides the selection of the current date and displaying the date. The setOnDateChangeListener Interface is used which provide onSelectedDayChange method. onSelectedDayChange: In this method, we get the values of days, months, and years
3 min read
Android - Line Graph View with Kotlin
Graphs are used in android applications to display vast amounts of data in an easily readable form. There are different types of graphs used such as BarGraph, GroupBar graph, point, and line graph to represent data. In this article, we will take a look at How to use Line Graph View in Android using Kotlin. A sample video is given below to get an id
3 min read
How to implement View Shaker in Android
View Shaker is an animation in which, the UI of screen vibrates for a limited period of time. This can be implemented on the whole layout or some particular widget. It is a very common effect that developers use, especially to show incorrect credentials. View Shaker helps us to animate the widgets. Various effects can be added to it. Effects Attent
3 min read
How to Add a Custom View Inside ActionBar in Android?
In Android, an Action Bar, or an app bar is a dedicated space at the top of the application on the screen that indicates the name of the application or activity. An Action bar helps users navigate or locate themself in the application. A sample Action Bar is shown in the below image. In this article, we will show you how you could customize the Act
3 min read
How to add KenBurns View in Android?
In this article, we will learn about how to add KenBurns View in android using java. KenBurns View is a useful library that is an extension of ImageView. It creates an immersive experience by animating its Drawable. We can use RandomTransitionGenerator to change the duration and acts as a interpolator of transitions. If we want to have more control
2 min read
View Recycling in Android with ListView
Memory management is a crucial aspect of app development. Since mobile devices have very limited memory, it is necessary to use it carefully in our applications. One of the best practices involved in doing so is "view recycling". This article is about view recycling in Android and then a simple app is created which implements the practice of view r
4 min read
Elastic View in Android
In this article, ElasticView is added in android. The ElasticView is a regular CardView, which can flex from user touches. OnClickListener and other various important methods can also be added to the child view of ElasticView. It makes the user interface more attractive thereby enhancing the user experience. Approach: Step 1: Add the support librar
2 min read
Double-Tap on a View in Android
Detecting a double tap i.e. whenever the user double taps on any view how it is detected and according to the view a response can be added corresponding to it. Here an example is shown in which the double tap on the view is detected and corresponding to it a response is added in the form of toast. Step 1: Create an Empty activity in Android Studio.
2 min read
Triple-Tap on a View Using onTouchListener Object in Android
To detect a triple tap i.e. whenever the user triple taps on any view how it is detected and according to the view a response can be added corresponding to it. Here an example is shown in which the user triple taps on the view, it is detected and corresponding to the view response is added in the form of toast. Step 1: Create an Empty activity in A
2 min read
Count the Number of Taps (Multi-Tapping) on a View in Android
In this article, the number of taps that user does in a short span of time on a particular view is counted, It can be used for adding different response with different taps. For example one tap on the word will show the meaning of the word while double tap will show its synonyms in a dictionary app. Below is an example in which the number of taps d
3 min read
Different Ways to View Contents of Database File in Android Studio
Data is a group of information and it can be any kind of information - text, numbers, image, video. An organized collection of this data is called a Database. It is made so that the data can be accessed and managed easily. Data can be organized into tables, rows, columns as that make it easier to handle the data. The main purpose of having a databa
4 min read