Android support ViewPager holds reference to old fragments

I was implementing a feature where I have a service that retrieves data on background and an activity receives results and updates one of the fragments with new data.

Everything went well until I rotated the screen and the application was re-created and fragments and fragments pager was initialized again. After that new data did not show up. At that point I was totally uncertain what was wrong. At first I was thinking the problem was with the service, but it turned out that nothing was wrong there. After struggling a while I noticed that the fragment that was  re-created was not attached to the view at all.

That led me to this Stack Overflow question and one answer provided a solution for me as well. The problem lies on Compatibility library v.4 ViewPager (bug report) combined with FragmentPagerAdapter. In some level ViewPager or FragmentPagerAdapter holds references to old fragments and does not refresh them correctly.

One working solution is to use FragmentStatePagerAdapter instead of FragmentPagerAdapter. However I resolved my issue with the help of this answer.

I implemented getFragmentTag() method in my FragmentPagerAdapter class

private String getFragmentTag(int pos){
    return "android:switcher:"+R.id.viewpager+":"+pos;
}

change R.id.viewpager to match with you ViewPager compnent’s id.

Then in my Activity I find reference to the Fragment like this.

...
this.mPagerAdapter  = new MyPagerAdapter(getSupportFragmentManager(), fragments, titles);
this.pager = (ViewPager)super.findViewById(R.id.viewpager);
this.pager.setAdapter(this.mPagerAdapter);
int position = 3;
this.myFragment = (MyFragment)getSupportFragmentManager().findFragmentByTag(mPagerAdapter.getFragmentTag(position));
...

And after service returned new data I simply call

...
myFragment.updateData(data);
...

Hopefully this saves someones time to figure out what is wrong instead of hours of investigation.

Advertisements