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
I don't know if this is the best way or not Bu I have been searching on google for quite a while finding how can I pass a Bundle from a fragment to its container activity but all I found was sending data from activity to fragment instead (which was a bit confusing for me as I'm a newbie).
later I tried something own my own that exactly worked for me as I wanted. so I'll post it here case someone like me looking for the same thing.
// Passing data from Fragment .
// Getting data from the bundle from it's container activity .
Another simple way to get datas, passed from another activity, in a fragment in a container activity : for example :
In your Activity_A you create an intent like you're sending a data (String here) to another activity :
in your Fragment, contained in your Activity_B :
This is working for me..
in Activity add this method
and in Fragment add this line
Interface is one of the best solutions:
Glue Interface:
MyActivity:
MyFragment:
I used an AppCompatActivity that implements Date Listeners. Fragments came as a necessity since I needed to code a date range selector. And I also needed the container to receive the selected dates to return them to the parent activity.
For the container activity, this is the class declaration:
And the interfaces for the callbacks:
The callbacks are strings because dates are params in an query select.
The code for the fragments (based on the initial date fragment):
}
To compose the container + fragments, I used an ViewPager (AppCompat) with a custom class that extends FragmentPagerAdapter. No dialogs.
In your fragment you can call
getActivity()
.This will give you access to the activity that created the fragment. From there you can obviously call any sort of accessor methods that are in the activity.
e.g. for a method called
getResult()
on your Activity: