1

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.

Jade McGough
  • 348
  • 2
  • 13

1 Answers1

1

OnSelect(page2 ) when you do the API calls and get your API call result , there should be a callback to update an object referenced by the API for 'OnSaveInstanceState'.

If you do that then IMO , here is what u get from the framework:

API returns results

results update a fragment that fragment gets processed by any call to 'OnSaveInstanceState'

OnOrientationChange :: with condition that it occurs AFTER the API returns results Fragment is saved with state reflecting the API results

Activity is recreated due to Orientation change on SavedInstanceState != null it reinstantiates the fragment from the state including the residue of the earlier api call....

see accepted answer here for additional detail

Community
  • 1
  • 1
Robert Rowntree
  • 6,230
  • 2
  • 24
  • 43
  • thank you - I'm doing some reading on onSaveInstanceState, looks like a good approach for my problem. I'll accept after I've tried it out. – Jade McGough Dec 06 '13 at 02:05