Reputation: 2333
So I've been struggling with this for a while. I'm a pretty new android developer, so understanding some concepts to me are still very difficult.
In my layout I'm using a PagerAdapter to swipe horizontally between pages. I want to have a button in the landing layout, when clicked, to scroll to an adjacent layout.
Now my problem is that I'm getting a NPE once I click that button. So I see the problem, but don't know how to write it to make it do actually what it's supposed to.
Here's my code.
public class CustomPageAdapter extends PagerAdapter {
ViewPager mPager;
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0: {
resId = R.layout.field01;
break;
}
case 1: {
resId = R.layout.add_site;
break;
}
case 2: {
resId = R.layout.main;
break;
}
}
View view = inflater.inflate(resId, null);
if (position == 1) {
Button addSiteButton = (Button) view.findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(2); //NPE happens here.
}
});
}
((ViewPager) collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public int getCount() {
return 3;
}
}
Thanks in advance!
Upvotes: 1
Views: 1160
Reputation: 977
The NPE is occurring because you are trying to access mPager which is just a reference and not pointing to anything, created by line: ViewPager mPager;
You will need to retrieve the viewPager from layout in mPager reference as:
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
Upvotes: 1