title: Passing data or behaviour between activities and fragments
body: <p>I have this structure:</p>
  
  <p>Activity A has a ViewPager. The pages of a ViewPager are as known Fragments.</p>
  
  <p>Activity A has a list of complex objects, which I want to display in the pages.</p>
  
  <p>When the user clicks on an item inside the ViewPager activity B must be started. Activity B also needs the list with complex objects.</p>
  
  <p>So I have to pass this list </p>
  
  <p>A -> Fragment(s) -> B</p>
  
  <p>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.</p>
  
  <p>But I don't want to serialize or parcel whole list of complex data 2 times only to get it through to B.</p>
  
  <p>I would like to avoid using static fields.</p>
  
  <p>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!).</p>
  
  <p>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?</p>
  
  <p>How do I solve this?</p>
  
  <p>Edit</p>
  
  <p>I found this solution in a thread about dialog fragments: <a href="https://stackoverflow.com/questions/9776088/get-data-back-from-a-fragment-dialog-best-practices">Get data back from a fragment dialog - best practices?</a></p>
  
  <pre><code>@Override
  public void onAttach(Activity activity) {
  super.onAttach(activity);
  try {
      mListener = (OnArticleSelectedListener) activity;
  } catch (ClassCastException e) {
      throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
  }
  }
  </code></pre>
  
  <p>So I add this to my fragment and make my activity implement certain interface.</p>
  
  <p>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...</p>
  
  <p><strong>Edit</strong>: I tried <strong>Parcelable</strong>, 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 <strong>pain</strong>. Maybe I just stick to static data...</p>