I'm creating an app which (according to chosen mode) has to have 2 or 3 tabs in a tabbed activity. When I choose the mode with three tabs, everything's fine, but mode requiring 2 tabs throws this exception:
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 3, found: 2 Pager id: abm.ant8.sotgtests:id/container Pager class: class android.support.v4.view.ViewPager Problematic adapter: class abm.ant8.sotgtests.MainActivity$SectionsPagerAdapter
When I comment out this.notifyDataSetChanged() (marked HERE), it crashes on both cases. Here's my PagerAdapter code (I'm using v4 support package):
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
mExplanationFragment = ExplanationFragment.newInstance();
mQuestionFragment = QuestionFragment.newInstance(totalNoOfQuestions);
if (mode == LEARNING_MODE) {
mRulesFragment = RulesFragment.newInstance();
}
Fragment fragment;
if (mode == TESTING_MODE) {
if (position == 1) {
fragment = mExplanationFragment;
} else {
fragment = mQuestionFragment;
}
} else {
if (position == 2) {
fragment = mExplanationFragment;
} else if (position == 1){
fragment = mQuestionFragment;
} else {
fragment = mRulesFragment;
}
}
//this.notifyDataSetChanged(); HERE
return fragment;
}
@Override
public int getCount() {
if (mode == TESTING_MODE) {
return 2;
} else {
return 3;
}
}
//...
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
This is already after applying hints from this SO topic, others looked very similar. Is this approach (taken directly from Android Studio wizard) correct at all for this situation? Looks like defining default start tab as middle, instead of the first one, is going to be a hassle as well (but that's of course for another question, after I solve this problem).
EDIT: as a brute-force solution, I'm thinking of simply copying the current Activity and slightly modifying it, so that it won't be an Activity called with extras in intent, rather calling different Activities. Since most of the needed functionality is already implemented (and much of it in fragments), this is definitely the fastest way to go. To keep it modular and clean I can just do some refactoring and move methods common for both Activities into separate class.