0

I'm using android.support.v4.view.ViewPager and noticed, that after setting my android.support.v4.app.FragmentStatePagerAdapter on the ViewPager in the onStart()-method of my activity I can't retrieve a view of the currently displayed ViewPager page, because it doesn't seem to be initialized/attached/drawn to the activity yet. I always get a NPE.

Is there an event which is fired, when my ViewPager is fully initialized including its fragment pages and their views?

My code in the onStart()-method of the main activity looks something like this:

ViewPager vp = findViewById(R.id.viewPager);
vp.setAdapter(new FlashCardPagerAdapter(getSupportFragmentManager()));
vp.getChildCount(); //this is still 0 because the child fragments have not been added yet, why? When are they added?

My Adapter looks like this:

public class FlashCardPagerAdapter extends FragmentStatePagerAdapter {

    private List<FlashCard> flashCards;
    private FlashCardFragment[] flashCardFragments;

    public FlashCardPagerAdapter(FragmentManager fm) {
        super(fm);

        flashCards = FlashCardApp.getInstance().getFlashCards();
        flashCardFragments = new FlashCardFragment[flashCards.size()];
    }

    @Override
    public Fragment getItem(int i) {
        if (flashCardFragments[i] != null) {
            return flashCardFragments[i];
        } else {
            flashCardFragments[i] = new FlashCardFragment(flashCards.get(i));
            return flashCardFragments[i];
        }
    }

    public FlashCardView getFlashCardViewAt(int i) {
        return ((FlashCardFragment) getItem(i)).getFlashCardView();
    }

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

Thanks for any help.

EDIT Thing is, all this works when I call it after the onStart() method, for example in one of my custom button views.

crisi
  • 73
  • 2
  • 10

1 Answers1

0

I'm guessing vp.setAdapter(new MyAdapter()); is just a typo and you meant to say vp.setAdapter(new FlashCardPagerAdapter(getSupportFragmentManager()));

If that doesn't work, then it's returning 0 pages for some reason. I would check the adapter's getCount() method to make sure it's returning something more than 0, because that's how the viewpager decides how many pages to show.

Gak2
  • 2,661
  • 1
  • 16
  • 28
  • Yes it's a typo. I fixed it. My getCount() method works as expected and returns a value of 25. – crisi Oct 25 '13 at 17:58
  • it might have something to do with you using FragmentStatePagerAdapter instead of FragmentPagerAdapter? I know the prior doesn't store all the views in memory, unlike the latter. Also, are you using the adapter's getFlashCardViewAt(), or a viewpager method to retrieve the view? – Gak2 Oct 25 '13 at 18:13