How can I pass data between a fragment and its container activity? Is there something similar to passing data between activities through intents?
I read this, but it didn't help much:
http://developer.android.com/guide/topics/fundamentals/fragments.html#CommunicatingWithActivity
Passing data between a fragment and its container activity
Activity:
Fragment:
Reading the value in the fragment
Easiest Approach but not Recommended
You can access activity data from fragment:
Activity:
Fragment:
Simply you can use EventBus it is easy and work great
EventBus in 3 steps
Define events:
public static class MessageEvent { /* Additional fields if needed */ }
Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:
Post events:
EventBus.getDefault().post(new MessageEvent());
Try using interfaces.
Any fragment that should pass data back to its containing activity should declare an interface to handle and pass the data. Then make sure your containing activity implements those interfaces. For example:
In your fragment, declare the interface...
Then, connect the containing class' implementation of the interface to the fragment in the onAttach method, like so:
Within your fragment, when you need to handle the passing of data, just call it on the dataPasser object:
Finally, in your containing activity which implements
OnDataPass
...