How to transfer data from activity to fragment , and from fragment to fragment using a View Model
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.
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)
We are storing two data values :
- The first name
- 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 :
- 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
Steps to access view model from activity:
- Create a ViewModel variable (line 8)
- Reference it (line 16)
Steps to access ViewModel from fragment:
- Initialize a variable (line 5)
- 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 !