I have this structure:
Activity A has a ViewPager. The pages of a ViewPager are as known Fragments.
Activity A has a list of complex objects, which I want to display in the pages.
When the user clicks on an item inside the ViewPager activity B must be started. Activity B also needs the list with complex objects.
So I have to pass this list
A -> Fragment(s) -> B
First I found out that it's not possible to use the fragment's constructor to pass data to it. I have to use parcelable or serializable. In the fragment I then have to parcel or serialize again to pass to B.
But I don't want to serialize or parcel whole list of complex data 2 times only to get it through to B.
I would like to avoid using static fields.
Then I came to the idea to pass a listener to the fragment, which listens to item click, and notifies my activity A and activity A then starts activity B with the data. This looks cleanest for me because A is actually the one the data belongs to, so A starts fragment with data, fragment comes back to A and then A starts B with data. I don't have to pass the data everywhere (serializing!).
But this doesn't seem to work, because how do I pass a listener to the fragment using serialization? What is wrong about using a listener in a fragment to come back to the activity?
How do I solve this?
Edit
I found this solution in a thread about dialog fragments: Get data back from a fragment dialog - best practices?
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
}
}
So I add this to my fragment and make my activity implement certain interface.
This would solve the problem of passing data from fragments to B. But I still need to pass the list from A to the fragments. Probably I'll have to use a Parcelable...
Edit: I tried Parcelable, it works. But the objects in my list have a lot of fields between them also maps, for example. Writing the Parcelable code (write / read) is a pain. Maybe I just stick to static data...