java.lang.IllegalStateException: Fragment no longer exists for key f1: index 3

Solution 1:

This could help -

@Override
public Parcelable saveState() {
    return null;
}

Add the line above in FragmentStatePagerAdapter.

Solution 2:

If you don't want the fragments to get reclaimed when they are offscreen, you should be using FragmentPagerAdapter and not FragmentStatePagerAdapter.

Solution 3:

Issue Detail

By default FragmentStatePagerAdapter will save and restore the state of ViewPager. While restore if fragment instance killed due to some reason then FragmentManger will throw this exception.

Solution:

To Fix this need to override the restoreState method in our FragmentStatePagerAdapter and put try catch block. It will prevent the crash and also it will retain the viewpager's fragment state for normal case.

@Override
public void restoreState(Parcelable state, ClassLoader loader) {
    try {
        super.restoreState(state, loader);
    } catch (Exception e) {
        Log.e("TAG", "Error Restore State of Fragment : " + e.getMessage(), e);
    }
}

Note: We can use FragmentPagerAdapter or Override saveState() and return null also fix this issue but viewpager will not retain its state for the normal case.

Solution 4:

if you are using ViewPager2 then use this method on ViewPager2 object

viewPager2.setSaveEnabled(false);

Solution 5:

I have struggle on this problem for whole day, but now I found the solution.

private ViewPager _mViewPager;
_mViewPager.setOffscreenPageLimit(5);
//5 is how much page you have.

setOffscreenPageLimit Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.