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.
The general idea is that I manage a SparseArray within the FragmentPagerAdapter, and then create an onPageChangeListener for the viewPager:
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);
}
}
});
I also overrided the instantiateItem and destroyItem in the FragmentPagerAdapter, to properly remove and re-add fragment references in my sparseArray.
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.
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.