How to use View Model Architecture Components to preserve the data of the Activity and Fragment

How to use View Model Architecture Components to preserve the data of the Activity and Fragment

In this tutorial, we will learn how to implement the View Model Architecture Components to preserve the data of the Activity and Fragment.  You know, Activity or Fragment is get created and destroyed very frequently whenever any configuration change has at the Android system level.  For example whenever you rotate the screen activity and fragment will go through the full lifecycle and it gets recreated again. In this scenario, all data of your UI element will get lost. So ViewModel is the solution to this problem.

Introduction

To clear the concept of View Model and implementation of it, we are making this tutorial very simple. In this, we will add two component a TextView and Button at layout layer.

When the user clicks on the Button TextView will show the number of clicks. What happens in this case at the screen rotation TextView click count get reset.  As the solution of this, we will implement the ViewModel so that number of click count stored into the variable of main activity should not get lost due to the configuration change.

Create the Layout File for View Model Activity

For this example, we need to create the Layout file of the activity. To create or modify the mainactivity.xml file as given below.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.nplix.datamodeltutorial.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/clickCount"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/clickMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@id/clickCount"
       />

</android.support.constraint.ConstraintLayout>

Create the MainActivity class without ViewModel Implementation

package com.nplix.datamodeltutorial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
private Integer clickMe=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnClickMe=findViewById(R.id.clickMe);
        final TextView txtClickMe=findViewById(R.id.clickCount);
        txtClickMe.setText("You Have Clicked " + clickMe + " Times");

        btnClickMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               clickMe++;
               txtClickMe.setText("You Have Clicked " + clickMe + " Times");
            }
        });
    }
}

Now run the application and click on the ClickMe button sometimes and rotate the screen after that. You can see the sample in below video.

As you can see in above video whenever you rotate the screen counter are getting reset. So to get out of this problem we are going to implement the View Model in our app. So that this counter should not get reset in any configuration change.

Prerequisite for View Model

So for implementing the View Model, we required AndroidStudio 2.3 or later.

Library required for Architecture Components View Model

We need to add the dependency to our app level build.gradle project as given below.

implementation "android.arch.lifecycle:extensions:1.0.0"
    annotationProcessor "android.arch.lifecycle:compiler:1.0.0"

This library is available through google repository so you may need to add the google() into the project level build.gradle project. So modify your build.gradle file as given below and add the google() repositories.

buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Create the Architecture Components View Model class

We need to create a View Model class by extending the ViewModel root class. Here in this example, we are creating the ClickMeViewModel class. To create and modify the ClickMeViewModel.java file as given below.

package com.nplix.datamodeltutorial;

import android.arch.lifecycle.ViewModel;

/**
 * Created by PK on 1/8/2018.
 */

public class ClickMeViewModel extends ViewModel {
    private Integer clickCount;

    public Integer getClickCount() {
        return clickCount;
    }

    public void setClickCount(Integer clickCount) {
        this.clickCount = clickCount;
    }
}

This class has one variable clickCount to store the number of clicks and two methods as getter and setter of the class.

MainActivity to store and retrieve data from ViewModel Class

First of all, we have to create an instance of our ClickMeViewModel class using the code below.

final ClickMeViewModel clickMeViewModel= ViewModelProviders.of(this).get(ClickMeViewModel.class);

Here final is not necessary it is only used because we have used this inside the onclick method of button click event.

Next check if View Model has some data using code. If it is not null then get the stored value from View Model and store it into clickMe variable else initialize with the default value.

// Check if View Model have some value
        if(clickMeViewModel.getClickCount()!=null){
            clickMe=clickMeViewModel.getClickCount();
        }
      //  else initialize with initial setup
        else{
            clickMe=0;
        }

Using below code we are storing the current value of clickCount into view model inside the onClick method of button onClick Listener.

clickMeViewModel.setClickCount(clickMe);

MainActivity class with ViewModel Implementation

After modification, our MainAcitivity.java file will look like as given below.

package com.nplix.datamodeltutorial;

import android.arch.lifecycle.ViewModelProviders;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
private Integer clickMe=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnClickMe=findViewById(R.id.clickMe);
        final TextView txtClickMe=findViewById(R.id.clickCount);
        final ClickMeViewModel clickMeViewModel= ViewModelProviders.of(this).get(ClickMeViewModel.class);
        // Check if View Model have some value
        if(clickMeViewModel.getClickCount()!=null){
            clickMe=clickMeViewModel.getClickCount();
        }
      //  else initialize with initial setup
        else{
            clickMe=0;
        }
        txtClickMe.setText("You Have Clicked " + clickMe + " Times");

        btnClickMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               clickMe++;
               txtClickMe.setText("You Have Clicked " + clickMe + " Times");
               //set the Click Count to ViewModel
               clickMeViewModel.setClickCount(clickMe);
            }
        });
    }
}

Now we have done with the simple implementation of View Model Architecture Components. Its time to test our app, Watch the below video to get the difference. Now when we rotate the screen or configuration change happen our counter will not reset.

Conclusion

In short, we can say that View Model is the solution to protect you Activity and Fragment on configuration change. You can go to the google doc if you want to learn more about ViewModel.

Further check out the next part of this tutoiral Lifecycle Aware Data and Configuration change handling with LiveData .

Download the source code of this Article from Github.

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

This Post Has 6 Comments

Leave a Reply

Close Menu