0

I have a scenario that i have one activity and 4 fragment , from one of the fragment i am passing the data using interface to the main activity , I am receiving the value or say object , now what i need to do , i have to pass the same object to all other fragment . but i don't wanna to use bundle or static method/field , I just want to know the best idea or approach to this question , what i can do ?

One solution i am thinking using the abstract class , Let's say my abstract class name is ParentFragmentAbstarct should implements the Fragment class and define a abstract method inside it let say setData(), then every Fragment should extends this Fragment class then abstract method is overridden in every fragment , now i am lost , how to set the value in it if i am getting the value only from one of the fragment(let's say from network response i am receiving the data in Fragment 2 n now how to set this same value in other three fragment)

Barnali Bhattacharjee
  • 497
  • 2
  • 10
  • 24

2 Answers2

0

Using Abstract Class with an Array of Fragment Object:

Like ViewPager you have an Adapter holding the instances of those fragments. When one of your fragments informs the MainActivity about the new data using Interface then you can simple iterate on ViewPagerAdapter and call your abstract Method. All the fragments will get notified.

Using Broadcast Receiver

You can declare your own broadcast receiver and made your fragments to listen to those broadcast. when the data is ready, your fragment can send a broadcast and all the other Fragments who are listening to this specific broadcast can thereafter update their state. Check this one

Using Observable RxJava

In ReactiveX an observer subscribes to an Observable. Then that observer reacts to whatever item or sequence of items the Observable emits. This pattern facilitates concurrent operations because it does not need to block while waiting for the Observable to emit objects, but instead it creates a sentry in the form of an observer that stands ready to react appropriately at whatever future time the Observable does so.

have a look at observable

Using EventBus

EventBus is a publish/subscribe event bus for Android and Java.

This is a great library, very small footprint and gets the job done with ease

Sahil Manchanda
  • 9,812
  • 4
  • 39
  • 89
0

You could create a singleton data manager class, and have all the fragments subscribe to it and listen for data changes. Each fragment can then have it's own implementation when recieving a state change.

Make any database calls in this manager class and distribute data to the listeners on response callbacks

hermt2
  • 844
  • 3
  • 14
  • 33