Tuesday 27 November 2018

Android Architecture Components : Live Data + View Model

Hi ,

In previous posts , I have described the properties of View Model and Live Data . But if we use both together , that would be great for an individual application. So here I am going to share a demo where we can see that how both will work together .

Firstly I am creating one layout having one TextView inside , named  view_model_layout.xml -> 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textview7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="25sp"
        android:textColor="#085937"
        android:textStyle="bold"
        android:text="TextView" />


</RelativeLayout>

Now Let's create one view model class , named as : RandomNumViewModel.java :


package com.development.view_model_live_data;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import java.util.Random;

public class RandomNumViewModel extends ViewModel {

    MutableLiveData mMutableLiveData;

    public RandomNumViewModel() {
        mMutableLiveData = new MutableLiveData<>();
    }

    private int[] items = new int[]{1, 2, 3, 44, 65, 87, 22, 65, 87, 22, 90, 63, 4, 8, 50};
    private Random random = new Random();
    /**
     * mRandomNumber , this variable should retain its value,
     * on configuration change
     */
    private int mRandomNumber = 0;

    /**
     * used to create a random number from array
     * @return
     */
    public int createNumber(){
        mRandomNumber = items[random.nextInt(items.length)];

        return mRandomNumber;
    }

    /**
     * used to get the random number
     * @return
     * @param txt
     */
    /**
     * Observe the random number
     */
    public MutableLiveData getRandArrayElement(){
        if(mRandomNumber == 0){
            mRandomNumber = createNumber();
        }
        mMutableLiveData.setValue(mRandomNumber);
        return  mMutableLiveData;
    }
}


And the Activity class will only be observe the changed value of mRandomNumber , let's have a look on Activity class, named ViewLiveDemoActivity.java:

package com.development.view_model_live_data;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.development.R;

public class ViewLiveDemoActivity extends AppCompatActivity {
    TextView txt;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_model_layout);
        txt  = (TextView)findViewById(R.id.textview7);
        RandomNumViewModel randomNumViewModel = ViewModelProviders.of(this).get(RandomNumViewModel.class);
        randomNumViewModel.getRandArrayElement().observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                txt.setText(""+ o);
            }
        });
    }
}

Here you can see that , activity class only notify when variable value has been changed , and this is done by Live Data concept . If we rotate our device , then the value of variable will not be changed , this concept has been done by View Model . I have attached the screenshots for portrait and landscape modes for better understanding :

 Portrait Mode


Landscape Mode






Here in above images you can see that the variable value remains same after the rotation of device . And this all has been done both using Live Data +View Model . You can take this code and run it by yourself  . Happy Coding :) 

No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...