0

I tried to follow a tutorial how to create a swipeable ViewPager with ActionBar Tabs. Everything is compiling fine, but when I try to start the activity, it crashes with this error:

Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference

This is my adapter:

public class TabsPagerAdapter extends FragmentPagerAdapter {

public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        return new WeekFragment();
    case 1:
        return new MonthFragment();
    case 2:
        return new YearFragment();
    }

    return null;
}

@Override
public int getCount() {
    // get item count - equal to number of tabs
    return 3;
}}

Part of my MainActivity:

viewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);

I know this question has been asked many times ago, but nothing works. I don't know, why this is not working! Please help me. I'm now sitting here for more than 2 hours and still haven't found a solution ...

  • check if the layout file of your mainactivity got a viewpager with the id 'pager', that would be my guess – mrtn Jun 03 '15 at 22:48
  • Yes, of course it has. And otherwise it also wouldn't have compiled properly, I think. But yes, there is a ViewPager called "pager". This is the reason why there is no point for me to come further. – Jan Temešinko Jun 03 '15 at 22:52
  • You can try to debug and check if viewPager is null after viewPager = (ViewPager) findViewById(R.id.pager);.I guess that viewPager is already null at that point. – mrtn Jun 03 '15 at 23:08
  • I found my fault. I set the wrong contentView *facepalm* – Jan Temešinko Jun 04 '15 at 00:18

1 Answers1

0

Okay, now I found out why this error happened. I set the wrong contentView. Therefore viewPager was indeed null. Smallest things make biggest problems.

Anyway, thank you for your help, guys!

Perhaps someone has the same problem I had.