I want to understand this exception in order to implement a proper fix.
There\'s a ViewPager and it uses a FragmentStatePagerAdapter to instantiate 2 fragments via g
Use
getFragmentManager()
in fragment adapter not child fragment manager
PagerAdapter adapter = new PagerAdapter(getFragmentManager());
I hope this helps.
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.