1

Everytime i am in need of having a shared data to use or to be updated in fragment, i always put the data in activity and create a method to get/update the data then access it in fragment through something like this

(activity as HomeActivity).updateData()

i feel like this is not the good way to do this, is there any better way to do this? having the same object to be accessed through different fragment

I am a newbie so any advice will be really appreciated, Thanks

Jolzal
  • 547
  • 7
  • 19
  • Does this answer your question? [How to pass data between fragments](https://stackoverflow.com/questions/5194548/how-to-pass-data-between-fragments) – jsamol Jan 04 '20 at 10:00

2 Answers2

1

Whenever you replace fragment from Activity or from anywhere you can pass data to fragment by setting data as Arguments.

   Testfragment = new TestFragment();
   Bundle bundle = new Bundle();
   bundle.putSerializable("key",<data to pass>);
   fragment.setArguments(bundle);
   replaceFragment(fragment);

Access same data in fragment by using

      Object obj = getArguments().getSerializable("key")
PlusInfosys
  • 3,416
  • 1
  • 19
  • 33
1

Please try the following:

  1. Create a singleton class
  2. In the singleton class create empty or valued variables
  3. Create getter/setter for those variables if required
  4. Access the variables from other classes/activities using the singleton object of the data holder class

This a system from MVP/MVC architecture and a very good practice

Saswata
  • 1,290
  • 2
  • 14
  • 28