What is the current best practice of passing Data from one activity (master) to another (detail).
a possible approach could be to have a single view model class that's shared between the master and detail. When clicking on an item in the master activity the selected entry will be set to the view model. The detail activity, thereby can read the selected entry, because it's using the same view model.
Pass the row-id of the selected object from the master-activity as an bundle-extra to the detail activity. The detail activity loads it's view model by using ViewModelProviders
and afterwards passes the row-id to the view-model which loads the actual record.
Initiale the view model before starting the detail activity and set the selected object directly to the initialized view model of the detail activity.
Input would be very much appreciated!
We can send the data using the putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.
In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.
To pass data from the Main View/Main ViewModel to the Detail ViewModel, assign the data to the ViewModelExtensions. Parameter attached property on the Detail View instance.
Passing Data between fragments in Android using ViewModel: This is because ViewModel is tied to the activity lifecycle. To actually pass the data between fragments, we need to create a ViewModel object with an activity scope of both the fragments, initialize the ViewModel , and set the value of the LiveData object.
I had the same question, and it was answered perfectly by Lyla Fujiwara's article ViewModels: Persistence, onSaveInstanceState(), Restoring UI State and Loaders. The article discusses the different ways you can persist data and which is best fit for a given occasion.
Do ViewModels persist my data? TL;DR No. Persist as normal!
Are ViewModels a replacement for onSaveInstanceState? TL;DR No, but they are related so keep reading.
How do I use ViewModels to save and restore UI state efficiently? TL;DR You use a combination of ViewModels, onSaveInstanceState() and local persistence.
Are ViewModels a replacement for Loaders? TL;DR. Yes, ViewModels used in conjunction with a few other classes can replace Loaders.
Those are here succinct answers to questions tangential to what you're asking. If you read the actual article, she gives explanations for each.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With