I have been working on the implementation of buttons to update a textview within my pageadapter. This is the code I have thus far for my pageadapter
public class CharacterStatsPagerAdapter extends PagerAdapter {
public int getCount() {
return 2;
}
int maxhp = 0;
View view = null;
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (position) {
case 0:
view = inflater.inflate(R.layout.characterstats1, null);
TextView characternamedisplay = (TextView) view.findViewById(R.id.textView1);
characternamedisplay.setText(com.echaractersheet.BasicInfo.characternameresult);
TextView genderdisplay = (TextView) view.findViewById(R.id.textView2);
genderdisplay.setText(com.echaractersheet.BasicInfo.genderresult);
TextView classdisplay = (TextView) view.findViewById(R.id.textView3);
classdisplay.setText(com.echaractersheet.BasicInfo.classresult);
TextView racedisplay = (TextView) view.findViewById(R.id.textView4);
racedisplay.setText(com.echaractersheet.BasicInfo.raceresult);
ImageButton plusmaxhp = (ImageButton) view.findViewById(R.id.imageButton1);
plusmaxhp.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
maxhp = maxhp + 1;
TextView maxhpdisplay = (TextView) view.findViewById(R.id.textView5);
maxhpdisplay.setText(maxhp);
}
});
break;
case 1:
view = inflater.inflate(R.layout.characterstats2, null);
break;
}
((ViewPager) collection).addView(view, 0);
return view;
}
The first 4 textviews update perfectly fine but the problem comes in with my imagebutton. When I click the button to update a characters hp, the program force closes and according to logcat, its a null pointer exception and I am unsure why it is happening.
I have been referencing Button activity with viewPager? and How to write button onClick method in viewpager? but have been having little success to getting rid of my null pointer exception.
Any help would be greatly appreciated. Thank you!
Have fixed Your code.
Please, refer below:
Seems the issue was in the following: You’ve used the same variable for both view. If pager at first makes call to obtain first item and later – second one, then Your variable will hold reference to second item which doesn’t have textView5 in where.