FragmentPagerAdapter doesn't respond to notifyDataSetChanged()

Filed Under: android (tips)

Oct 31 2011

Sorry, this fix is no longer relevant. Recent versions of the support library no longer export a DataSetObserver in PagerAdapter.

Recently, I came across a pretty annoying issue with the FragmentPagerAdapter in the Android Compatibility Library (v4, released in October 2011). If you change any data in the child fragments of the ViewPager and call notifyDataSetChanged(), nothing happens. The PagerAdapter relies on data inside the FragmentManager instead of rebuilding fragments through the getItem() call. It seems others have faced this issue as well:

Looking through the source code, it looks like there is no default DataSetObserver. Worse is the fact that the DataSetObserver interface is private to the Android Compatibility Library so you can't even supply your own ! Luckily, a workaround can be found as follows: Create a new class called PagerAdapterCompat with the package name

<?prettify?> package;

public abstract class FragmentPagerAdapterCompat extends FragmentPagerAdapter {
    public FragmentPagerAdapterCompat(FragmentManager fm) { super(fm); }

    public interface DataSetObserver extends PagerAdapter.DataSetObserver {}

    public static void setDataSetObserver(PagerAdapter adapter, DataSetObserver observer) {

Don't forget to hit Ctrl+Shift+O in eclipse to get those imports added :-) After this, you can simply create your own DataSetObserver (I made mine pretty basic by calling destroyItem() on each page) and set it with FragmentPagerAdapterCompat.setDataSetObserver(your_adapter, your_observer); All credit goes to this guy for reporting the bug and providing a quick and easy solution: (although his is more general for the PagerAdapter) Please head on over there to star the bug so that it get's more attention!