Search code examples
androidandroid-viewpagerandroid-pageradapterfragmentstatepageradapter

FragmentStatePagerAdapter first call to getItem wrong with sdk 22-->23 upgrade


UPDATE 2: Getting rid of all v4 support references fixed it. UPDATE: I started from scratch to see what triggers this behavior. It occurs once I add a check for location permissions. I can't go backwards -- even when I strip out all the permissions code it stays with the incorrectly-bahaving FragmentStatePagerAdapger.

I have a FragementStatePagerAdapter that was working just fine for a ViewPager of dynamically created fragments until I changed my compileSdkVersion and target SdkVersion from 22 to 23, using appcompat-v7:23.2.1. Now if I attempt to load, say, A, B, C it loads B, B, C. But then if I swipe back I get C, B, A. So it is only the initial attempt to load dynamically-created fragment A that is unsuccessful.

Here is how I set my adapter and viewpager:

myAdapter = new MyAdapter(getSupportFragmentManager(), numItems);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(myAdapter);
viewPager.setCurrentItem(position);

MyAdapter:

private class MyAdapter extends FragmentStatePagerAdapter {
    private final int size;

    public MyAdapter(FragmentManager fm, int _size)  {
        super(fm);
        size = _size;
    }

    @Override
    public int getCount() {
        return size;
    }

    @Override
    public Fragment getItem(int position) {
        String _id = myArray[position];
        return MyFragment.newInstance(_id);
    }
}

And instantiating the Fragment:

public static MyFragment newInstance(String _id)  {
        final MyFragment f = new MyFragment();
        final Bundle args = new Bundle();
        args.putString("_id", _id);
        f.setArguments(args);
        return f;
    }

...

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _id = getArguments().getString("_id");            
    }

Has anyone else experienced this after upgrading? I am at a total loss after spinning my wheels on this for hours.


Solution

  • The idea that I posted as a comment resolved the problem, here is the same answer with a few more details...

    Short version: in adapters derived from FragmentStatePagerAdapter, try to use FragmentManager instead of SupportFragmentManager. Unless you're 100% sure you need the SupportFragmentManager.

    Explanation:

    code in the question looks pretty good. The only place where adapter can 'confuse' fragments is the method instantiateItem(ViewGroup container, int position). This method uses a FragmentManager passed as an argument of constructor. So we can blame that suspicious SupportFragmentManager.