Skip to main content

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.

Comments

  1. […] LiveData is the class which can be observed and ViewModel is the class which can hold the data of the activity and fragment. In simple we can say ViewModel store the data and LiveData will keep eyes on those data. In case of any change immediately notify the bound activity and fragment. If you want to learn more about the ViewModel kindly refer our earlier tutorial about ViewModel. […]

    ReplyDelete
  2. […] If you want to learn about the LiveData and ViewModel you can check out the article on LiveData and ViewModel which we published […]

    ReplyDelete
  3. […] How to use View Model Architecture Components to preserve the data of the Activity and Fragment  […]

    ReplyDelete
  4. […] try to fetch the details from the server. As solution of this problem we are going to implement the ViewModel and LiveData architecture component to our […]

    ReplyDelete
  5. […] Architecture Components Library for MVC app development.  Architecture Components Library includes ViewModel, LiveData, RoomDatabase and Paging Library. In this article, we will create a TODO app that loads […]

    ReplyDelete
  6. […] the changes using the ViewModel and its observer and In case of any change in the data of the ViewModel, UI will get […]

    ReplyDelete

Post a Comment

Popular posts from this blog

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View. Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android Just go to the android folder and open it in separate windows. We will have the following project structure. Create the Activity Just right-click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project s

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface

Create Custom EditText View in Android

We use the EditText for taking the input from the user and use it at several places in our project. We required to do lots of customization for each time and there are lots of redundant code we write. Writing and managing these redundant codes is very difficult for example if we want to change the look and feel of the view them we need to modify it at each place where our EditText is getting used. So to avoid these kinds of the problem we can create our own Custom EditText View by just. The EditText view is just an extension of the TextView with lots of editing option and properties that required for the user input. How To Create Custom EditText View For creating the Custom EditText we need to extend the AppCompatEditText and override all three constructors of the view as given below. import android.content.Context; import android.graphics.Typeface; import android.support.annotation.Nullable; import android.support.v7.widget.AppCompatEditText; import android.util.AttributeSet; public