Android

Understanding LiveData With Basic Example

Pinterest LinkedIn Tumblr

LiveData is the main component of core architecture as like RxAndroid, Dagger, and other core components. LiveData helps to reduce memory leaks and manual lifecycle handling. It ensures that UI is up to date with your data state.

In the ReactiveX tutorial, we learned how observable patterns work? Like RxJava, LiveData follows the observer pattern, it notifies the UI class if any change happens in the Data state.

Benefits of LiveData

  • UI is up to date with the data state
  • No memory leaks
  • Proper configuation changes
  • No crashes due to stopped activities
  • Sharing resources
  • No more manual lifecycle handling

In this example, we’re going to implement basic increments and decrement the counter. Look at the demo, please

View model demo

Why we’re waiting? let’s start the implementation of this demo

1- Open the Android Studio and create a new project.

2- Go to the project build.gradle.xml file and add the below dependencies.

dependencies {
    def lifecycle_version= "2.3.1";
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

3- Go to res->value and open the colors.xml file if you want to keep it like demo and add the below code.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>

    <!-- App colors -->

    <color name="color_bg">#121212</color>
    <color name="color_tv">#02E2FF</color>
    <color name="color_btn">#444748</color>
</resources>

4- Open the res->values->strings.xml file and add the below code

<resources>
    <string name="app_name">Basic LiveData Example</string>
    <string name="str_likes">Likes</string>
    <string name="str_rest">Reset</string>
</resources>

4- Go to res->layout and open the activity_main.xml file and add the below code.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    android:background="@color/color_bg"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvHeading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="@string/app_name"
        android:textColor="@color/white"
        android:textSize="20sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imgLogo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:src="@drawable/app_logo"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvHeading" />


    <TextView
        android:id="@+id/tvLikesValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="0"
        android:textColor="@color/color_tv"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imgLogo" />


    <TextView
        android:id="@+id/tvLikes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_likes"
        android:textColor="@color/color_tv"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvLikesValue" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnMinus"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginTop="30dp"
        android:background="@drawable/bg_btn_with_circle"
        android:onClick="decLikes"
        android:text="-"
        android:textColor="@color/white"
        android:textSize="30dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toStartOf="@+id/btnAdd"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvLikes" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnAdd"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/bg_btn_with_circle"
        android:onClick="incLikes"
        android:text="+"
        android:textColor="@color/white"
        android:textSize="30dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/btnMinus"
        app:layout_constraintTop_toTopOf="@+id/btnMinus" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnReset"
        android:layout_width="180sp"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/btnAdd"
        android:background="@drawable/bg_btn"
        android:onClick="resetLikes"
        android:layout_marginTop="20dp"
        android:text="@string/str_rest"
        android:textColor="@color/white"
        android:textSize="20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

5- Create a new Java class called MainActivityViewModel.java. In this class, we’ll extend the LiveData class and create an immutable object of integer. This object will be responsible for the data state.

package com.example.livedataexample;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class MainActivityViewModel extends ViewModel {
    public MutableLiveData<Integer> integerLiveData = new MutableLiveData<>(0);

}

6- Open the MainActivity.java file and add the below code. In the MainActivity.java file, I declared the MainActivityViewModal.java object which is getting the input value from the user and notifying the UI.

package com.example.livedataexample;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private MainActivityViewModel incDecValModal;
    private int curLikes = 0;
    private TextView tvLikesVal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // initialize the view modal
        incDecValModal = new ViewModelProvider(this).get(MainActivityViewModel.class);
        Observer<Integer> observer = integer -> {
            tvLikesVal.setText(integer + "");

        };
        
        // Subscribing the observer
        incDecValModal.integerLiveData.observe(this, observer);
        initComponents();
    }


    /**
     * This method will call when user will click on the INC button.
     * @param view reference of INC button
     * Incrementing counter by one and telling to the view model.
     */
    public void incLikes(View view) {
        curLikes++;
        incDecValModal.integerLiveData.setValue(curLikes);
    }

    /**
     * This method will call when click on the DEC button
     * @param view reference of DEC button
     * Decrementing counter by one and telling to view model
     */
    public void decLikes(View view) {
        curLikes--;
        incDecValModal.integerLiveData.setValue(curLikes);
    }


    /**
     * This method will call when user want to reset the counter
     * @param view reference of the button
     * Reset the counter value and set this value to view model.
     */
    public void resetLikes(View view) {
        curLikes = 0;
        incDecValModal.integerLiveData.setValue(curLikes);
    }

    /**
     * Initializing the TextView widgets
     */
    private void initComponents() {
        tvLikesVal = findViewById(R.id.tvLikesValue);
    }
}

Thanks for reading the tutorial. Subscribe to my YouTube channel. Like and Share my Facebook page with your friends.

Write A Comment