title: Properly Interacting with fragments in FragmentPagerAdapter
body: <p>I'm using a FragmentPagerAdapter for an activity, to page between 3 fragments, in addition to a ViewPager. Based on input from the first fragment (markers on a google map), I'm making API requests when the user switches to fragment 2 or 3, and then updating those fragment views.</p>
  
  <p>The general idea is that I manage a SparseArray within the FragmentPagerAdapter, and then create an onPageChangeListener for the viewPager:</p>
  
  <pre><code>pager.setAdapter(pagerAdapter);
  pager.setOnPageChangeListener(new OnPageChangeListener() {
  
      @Override
      public void onPageSelected(int position) {
          if (position == 1) {
              SecondFragment fragment = (SecondFragment) pagerAdapter.getFragment(1);
              fragment.update(currentMarker);
          } else if (position == 2) {
              ThirdFragment fragment = (ThirdFragment) pagerAdapter.getFragment(2);
              fragment.update(currentMarker);
          }
      }
  });
  </code></pre>
  
  <p>I also overrided the instantiateItem and destroyItem in the FragmentPagerAdapter, to properly remove and re-add fragment references in my sparseArray.</p>
  
  <p>This works pretty well, but the issue is when I rotate my device when I'm on the second or third fragment page. It gives me a NullPointerException when trying to call a method on the fragment (in the activity's onPageSelected) - I'm guessing because the activity is recreated, those fragments haven't been created yet when onPageSelected triggers.</p>
  
  <p>I'm thinking that a better approach might be to come up with a way to have the fragments just make the API call when they're visible, instead of having the activity trigger it (which might be cleaner - less communication to/from fragments is typically better), but any advice would be appreciated.</p>