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 Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use.



Create a flutter project



So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter.



Once your project is created you will get the default counter app and you try running the app in the…

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 sync completed.
Update the project build config …

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit.
What is Retrofit?
If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps.

Further, you can check the Retrofit Library here.

So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website.
Prerequisite for using the Retrofit for WordPress Android App
There is s…