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

后端 未结 8 503
一整个雨季
一整个雨季 2020-12-24 10:43

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

相关标签:
8条回答
  • 2020-12-24 11:07

    Use

    getFragmentManager()

    in fragment adapter not child fragment manager

    PagerAdapter adapter = new PagerAdapter(getFragmentManager());
    

    I hope this helps.

    0 讨论(0)
  • 2020-12-24 11:12

    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.

    0 讨论(0)
提交回复
热议问题