Open In App

Jetpack LiveData in Android with Example

Last Updated : 25 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Android Jetpack is a suite of libraries to help developers follow best practices, reduce boilerplate code, and write code that works consistently across Android versions and devices so that developers can focus on the code they care about. Here, we are going to implement Jetpack Live Data in Android Studio.

What we are going to build in this article?

A sample video of what we are going to build in this article is shown below. Note that we are going to implement this project in the Java language.

Step by Step Implementation

Step 1. Create a New Project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • Name the application at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?  

Step 2. Adding required dependencies

Navigate to Gradle scripts > build.gradle(module) and use the following dependencies in it-

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

Step 3. Working on XML files

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingTop="16dp"
    tools:context=".MainActivity">
 
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_text"
        android:hint="Enter Text"
        android:paddingTop="12dp"
        android:background="@android:drawable/editbox_background"/>
   
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/frame_layout"
        android:layout_marginTop="16dp"/>
 
</LinearLayout>


 
 

Navigate to app > right-click > new > fragment > blank fragment. Name it as MainFragment and use the following code in fragment_main.xml file-

 

XML




<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainFragment">
 
   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/tv_result"
       android:textSize="40sp"
       android:textStyle="bold"
       android:gravity="center"/>
 
</FrameLayout>


 
 

Step 4. Working on Java files

 

Navigate to the MainActivity.java file and use the following code in it. Comments are added to the code to have a better understanding.

 

Java




package com.example.jetpacklivedata;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
 
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
 
public class MainActivity extends AppCompatActivity {
 
    // Initialize variables
    EditText editText;
    MainViewModel mainViewModel;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Assign variables
        editText=findViewById(R.id.et_text);
 
        // Initialize view model
        mainViewModel= ViewModelProviders.of(MainActivity.this)
                .get(MainViewModel.class);
 
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
 
            }
 
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // When text change
                // Update view model text
                mainViewModel.setText(String.valueOf(charSequence));
            }
 
            @Override
            public void afterTextChanged(Editable editable) {
 
            }
        });
 
        // Initialize fragment
        Fragment fragment=new MainFragment();
         
        // Open Fragment
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,fragment).commit();
    }
}


 
 

Navigate to the MainFragment.java file and use the following code in it. Comments are added to the code to have a better understanding.

 

Java




package com.example.jetpacklivedata;
 
import android.os.Bundle;
 
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
 
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
 
 
public class MainFragment extends Fragment {
 
    // Initialize variable
    TextView tvResult;
    MainViewModel mainViewModel;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Initialize view
        View view=inflater.inflate(R.layout.fragment_main, container, false);
 
        // Assign variable
        tvResult=view.findViewById(R.id.tv_result);
 
        // Check condition
        if(getActivity()!=null){
            // When activity is not null
            // Initialize view model
            mainViewModel= ViewModelProviders.of(getActivity())
                    .get(MainViewModel.class);
 
            // Set observer on get text method
            mainViewModel.getText().observe(getActivity(), new Observer<String>() {
                @Override
                public void onChanged(String s) {
                    // When text change
                    // set result text on text view
                    tvResult.setText(s);
                }
            });
        }
 
        // return view
        return view;
    }
}


 
 

Navigate to app > new > Java Class. Name it as MainViewModel and use the below code in the MainViewModel.java file.

 

Java




package com.example.jetpacklivedata;
 
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
 
public class MainViewModel extends ViewModel {
 
    // Initialize variable
    MutableLiveData<String> mutableLiveData
        = new MutableLiveData<>();
 
    // Create set text method
    public void setText(String s)
    {
        // Set value
        mutableLiveData.setValue(s);
    }
 
    // Create get text method
    public MutableLiveData<String> getText()
    {
        // return value
        return mutableLiveData;
    }
}


 
 

Here is the final output of our application.

 

Output:

 

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads