How to implement LiveData, ViewModel with Navigation Component in Android

In this android programming source code example, we are going to implement LiveData, ViewModel with Navigation Component in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to implement LiveData, ViewModel with Navigation Component in Android.

activity_main.xml

<?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">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph10"/>

</androidx.constraintlayout.widget.ConstraintLayout>

res/navigation/nav_graph10.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/nav_graph10"
    app:startDestination="@id/navFragment20">

    <fragment
        android:id="@+id/navFragment20"        android:name="com.bluapp.androidview2.BluetoothAndNavigation.NavFragment20"        android:label="fragment_nav_fragment20"
        tools:layout="@layout/fragment_nav_fragment20" />

</navigation>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProviders;

import android.os.Bundle;
import android.os.Handler;

public class BluetoothAndNavigationActivity20 extends AppCompatActivity {
    private Viewmodel20 viewmodel20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_and_navigation20);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                viewmodel20 = ViewModelProviders.of(BluetoothAndNavigationActivity20.this).get(Viewmodel20.class);;
                viewmodel20.updateName("Inducesmile");
            }
        }, 5000);

    }
}

Viewmodel20.java

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

public class Viewmodel20 extends ViewModel {
    private MutableLiveData<String> itemname = new MutableLiveData<>();

    public void updateName(String name){
        itemname.setValue(name);
    }

    LiveData<String> observeItemname(){
        return itemname;
    }
}

fragment_nav_fragment20.xml

<?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">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:text="Name"/>

</androidx.constraintlayout.widget.ConstraintLayout>

NavFragment20.java

import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

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

import com.google.firebase.database.DataSnapshot;

import javax.annotation.Nullable;

public class NavFragment20 extends Fragment {
    private TextView name;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Viewmodel20 viewmodel20 = ViewModelProviders.of(getActivity()).get(Viewmodel20.class);
        LiveData<String> liveData = viewmodel20.observeItemname();
        liveData.observe((LifecycleOwner) this, new Observer<String>() {
            @Override
            public void onChanged(String string) {
                if(string != null){
                    name.setText(string);
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_nav_fragment20, container, false);
        name = (TextView) rootView.findViewById(R.id.name);

        return rootView;
    }


}

app/build.gradle

implementation 'androidx.navigation:navigation-fragment:2.1.0-alpha06'
implementation 'androidx.navigation:navigation-ui:2.1.0-alpha06'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment