2

I am using a FragmentStatePagerAdapter in combination with a view pager, which is nested in a fragment on Android. Thus, I am using the ChildFragmentManager in combination with the FragmentStatePagerAdapter to create my fragments.

So far so good, but here is the problem:

  • If I open a different Activity without finishing the activity that hosts the fragment with the view pager and afterwards resume it, the fragment that was selected in the ViewPager is empty. If I switch the fragment in the ViewPager before I open the different Activity, this issue does not appear. After returning and seeing the empty Fragment in the ViewPager, I am still able to switch the next Fragments, but if I try to switch back to the empty Fragment, I get a NullPointerException. This issue does not occur if I switch between the Fragment hosting the ViewPager and a different Fragment or if I change orientations.

  • If I use the FragmentManager instead of the ChildFragmentManager, I do not have this issue when switching to a different Activity, but it will then occur if I switch between the hosting and a different fragment or if I change the orientation.

So here's what I already tried without any success: * Use FragmentStatePagerAdapter adapter and FragmentPagerAdapter * Use setRetainedInstance(true and false) * Use getChildFragmentManager() and getFragmentManager() * Override getItemPosition() return POSTION_NONE and use notifyDataChanged() in onResume()

The only thing that is currently doing the trick is recreating the PagerAdapter in onResume() and re-initializing the ViewPager, but I think that's really bad practice as everything needs to be recreated.

So is there somebody, who can explain to me how a correct implementation should look like, or why the fragments can become empty (they are not null, I checked that). I am searching for a more elegant solution rather than recreating everything each time I resume my activity.

Any help is really appreciated.

3
  • Just a shot in the dark. Seem to recall that creating the adapter in onCreate of the fragment holding the viewpager can help in some situations. Oct 30, 2014 at 16:12
  • can you maybe post some code for your adapter? I've been through hell on numerous occasions having similar issues using viewpagers
    – Chris
    Oct 31, 2014 at 15:04
  • have similar issue and still trying to find the solution...
    – Big Coach
    Sep 18, 2018 at 9:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.