I am writing an application that uses NFC to read some data stored on it. My application uses Fragments and Fragment don\'t come with onNewIntent() method. Since, the data I
This is an old question, but let me answer it in case anybody bumps into it.
First of all you have a bug in your code:
You can't register Fragments
as listeners inside Activity
the way you do it. The reason is that Activity
and Fragments
can be destroyed by the system and re-created later from saved state (see documentation on Recreating an Activity). When this happens, new instances of both the Activity
and the Fragment
will be created, but the code that sets the Fragment
as a listener will not run, therefore onNewBalanceRead()
will never be called. This is very common bug in Android applications.
In order to communicate events from Activity
to Fragment
I see at least two possible approaches:
Interface based:
There is an officially recommended approach for communication between Fragments. This approach is similar to what you do now in that it uses callback interfaces implemented by either Fragment
or Activity
, but its drawback is a tight coupling and lots of ugly code.
Event bus based:
The better approach (IMHO) is to make use of event bus - "master component" (Activity
in your case) posts "update" events to event bus, whereas "slave component" (Fragment
in your case) registers itself to event bus in onStart()
(unregisters in onStop()
) in order to receive these events. This is a cleaner approach which doesn't add any coupling between communicating components.
All my projects use Green Robot's EventBus, and I can't recommend it highly enough.