0

I have an activity with 3 fragments and I need to update fragExchangeHistory listView from DB when I add an object to database in fragCurrencyExchange. How could I do it?

Code: GitHub

Roo
  • 613
  • 1
  • 7
  • 24

3 Answers3

1

Use an EventBus like https://github.com/greenrobot/EventBus to communicate between fragments and other components. So when Fragment A update something in the database, you can fire an event to inform the other fragments about the changes.

sockeqwe
  • 15,574
  • 24
  • 88
  • 144
  • So i should define event and eventBus.register in Activity, event.post when I add an object to database and then I'll get an event that I defined called in activity? – Roo Mar 22 '15 at 12:46
  • It depends: For instance you could post the event in `MyDatabase.addExchange()` (at the end where data has saved successfully to database) and listen in the fragments that are interested in such an update like `FragExchangeHistory` Fragment. So you should register `FragExchangeHistory` in `Fragment.onCreateView()` and unregister in `Fragment.onDestroyView()`. A simply solution to react on the update event is to call `FragExchangeHistory.loadHistoryList()` which will load the (updated) data from the database – sockeqwe Mar 22 '15 at 12:53
0

Implement an Observer pattern between the activity and the fragments so you can notify when you add some new data up to the activity and from activity to fragments. In this way the notification flow is:

  • Fragment A adds data to the database.
  • Fragment A notifies to its Activity Observer that the data has been updated.
  • The Activity notifies all the other fragments that the data has been updated.

As you can see this couples quite a while your activity with the fragments so I usually use some kind of Event bus library like this or this that makes your code quite decoupled and easy to understand.

droidpl
  • 5,872
  • 4
  • 35
  • 47
0

Maybe you should use CursorLoader.A CursorLoader automatically re-runs the query when data associated with the query changes. You should check this from the Android Developer official site.

penkzhou
  • 1,200
  • 13
  • 30