Search code examples
javaandroiddatabasesharedpreferencesviewmodel

How can I store and update a common (temporary) data between activities and fragments in Android?


i have an application with multiple fragments and activities. I'm wondering if I can create a container class between fragments. (I want to save with set and pull with get)

For example, I will save the gender information of the user in the FragmentA class, and then I will use this information when I switch to FragmentB. In the same way; I will get the user's age, height, weight in FragmentC class. and then I will access this information in the FragmentE (Final) class and save it to the Room database. How can I do this? Could you please give an example in Java?

Note: I'm using Shared Preferencens but I want to look for a different method as I don't know if it works asynchronously or synchronously. For example, can we create such a container with ViewModel LiveData, store the data and access it from anywhere?


Solution

  • Shared ViewModel in Android to communicate with other fragments. You can save your all data in this SharedViewModel and acsess it in all the fragments.

    Please follow this link https://www.geeksforgeeks.org/shared-viewmodel-in-android/

    Here they have used two fragment which act as sender and receiver similarly you can create for your multiple fragments

    //Java Implementation of SharedViewModel

    Sharing data between fragments using new architecture component ViewModel