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     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     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:
Â
Â