I basically have a MainActivity that has multiple tabs. Each tab is a ShowListFragment and it extends Fragment. Now, each tab contains data that I fetch from a database. I have a MOVE-button that moves data from one tab to another in each Fragment:
@Override
public void onClick(DialogInterface dialog, int listIndex) {
database.add(listIndex,object);
database.remove(listIndex,object);
}
The fragment does not update directly, but after a few swipes in between the tabs (3 exactly). How do I force the Fragment to update instantaneous after I clicked the button? I don't want to manage it through onPageSelected in the ViewPager, since it does not update the fragment I'm currently on, but after I've swiped to the next fragment. And also I don't want to update the data after each swipe.
I know that I maybe need to use some kind of observer pattern like this: How do I make a Class extend Observable when it has extended another class too? But still, I'm still not sure how to update the fragment directly, and how to apply the observer/event pattern in my application.
Since the fragments can access the activity easily enough with
getActivity()
, I would make the activity be the central hub for dispatching updates.It sounds like you already have the persistence part handled with the database and all you need is some update events. So here goes:
Define a listener interface. I usually do this as an inner interface within the activity:
Add a data structure to your activity to keep track of listeners:
Don't forget to initialize in the constructor:
Add the register/unregister methods to the activity:
Add the event method to your activity:
Have your fragments implement DataUpdateListener:
and implement the method
Override
onAttach()
andonDestroy()
in the fragments to register/unregister:Fire the event in your fragment's UI update event: