IllegalStateException: The application's PagerAdapter changed the adapter's content without calling PagerAdapter#notifyDataSetChanged

Solution 1:

I had a hard time making my ViewPager working. At the end, it seems that the example in the documentation is wrong.

The addTab method should be as follows:

public void addTab(Tab tab, Class<?> clss, Bundle args) {
        TabInfo info = new TabInfo(clss, args);
        tab.setTag(info);
        tab.setTabListener(this);
        mTabs.add(info);
        notifyDataSetChanged();
        mActionBar.addTab(tab);
    }

Notice the order of the last three operations. In the original example, notifyDataSetChanged was called after the mActionBar.addTab function.

Unfortunately, as soon as you call the addTab on the ActionBar, the first tab you add is automatically selected. Because of this, the onTabSelected event is fired and while trying to retrieve the page, it throws the IllegalStateException because it notices a discrepancy between the expected item count and the actual one.

Solution 2:

I fixed it by callinig notifyDataSetChanged() once and just before next call of getCount():

private boolean doNotifyDataSetChangedOnce = false;

@Override
public int getCount() {

  if (doNotifyDataSetChangedOnce) {
    doNotifyDataSetChangedOnce = false;
    notifyDataSetChanged();
  }

  return actionBar.getTabCount();

}

private void addTab(String text) {

  doNotifyDataSetChangedOnce = true;

  Tab tab = actionBar.newTab();
  tab.setText(text);
  tab.setTabListener(this);
  actionBar.addTab(tab);

}

private void removeTab(int position) {

  doNotifyDataSetChangedOnce = true;

  actionBar.removeTabAt(position);

}