How to transfer data from activity to fragment , and from fragment to fragment using a View Model

Kundan Kumar
2 min readMay 14, 2018

With the help of this app ShareData I will be explaining how to transfer data in between activity and fragments and also among fragments by using a ViewModel.

Why use ViewModel

View models have a great advantage because they are unaffected by configuration changes, and they make the task of sharing data very easy.

src : https://developer.android.com/topic/libraries/architecture/viewmodel

About the App :

This app has one MainActivity , two fragments , and one view model, the picture shows the two fragments, within the MainActivity. (Sorry for the bad UI please ignore it)

The first two image is of the first fragment which has one edit text and one button to go into second fragment. The next two images are of second fragment which has one TextView to show data from previous fragment and two button , one to go back to previous fragment and other to complete data entry.

We are storing two data values :

  1. The first name
  2. The second name

The first name will be taken from first fragment and second from the second fragment.

All the data will be store in the ViewModel so we need to initialize it first.

Steps to add ViewModel in project :

  1. Add this dependency
dependencies {
def lifecycle_version = “1.1.1”
implementation "android.arch.lifecycle:extensions:$lifecycle_version
}

2. Create a new class named MyViewModel.java which extends ViewModel

View Model Class

Steps to access view model from activity:

  1. Create a ViewModel variable (line 8)
  2. Reference it (line 16)

Steps to access ViewModel from fragment:

  1. Initialize a variable (line 5)
  2. Reference view model (line 13)

To get data or store data simply use the getter and setter methods , this is applicable to both activity and fragments.

String firstName = viewModel.getFirstName();
viewModel.setFirstName("New Name");

That’s it, now we can easily share data in between activity and fragments.

It was my first technical blog , Please give some suggestions , all types of criticism is appreciated. Thank you !

--

--