Expected the adapter to be 'fresh' while restoring state

。_饼干妹妹 提交于 2020-08-06 20:02:36

问题


I have a viewpager2 with multiple fragments in FragmentStateAdapter. Whenever I try to open a new fragment and then go back to my current one with viewpager2, I get an exception:

Expected the adapter to be 'fresh' while restoring state.

It seems FragmentStateAdapter is unable to properly restore its state as it is expecting it to be empty.

What could I do to fix this ?


回答1:


So my problem was that I was creating my FragmentStateAdapter inside my Fragment class field where it was only created once. So when my onCreateView got called a second time I got this issue. If I recreate adapter on every onCreateView call, it seems to work.




回答2:


I encountered the same problem with ViewPager2. After a lot of efforts on testing different methods this worked for me:

public void onExitOfYourFragment() {
    viewPager2.setAdapter(null);
}

When you come back to the fragment again:

public void onResumeOfYourFragment() {
    viewPager2.setAdapter(yourAdapter);
}



回答3:


I was also getting this java.lang.IllegalStateException: Expected the adapter to be 'fresh' while restoring state. when using ViewPager2 within a Fragment.

It seems the problem was because I was executing mViewPager2.setAdapter(mFragmentStateAdapter); in my onCreateView() method.

I fixed it by moving mViewPager2.setAdapter(mMyFragmentStateAdapter); to my onResume() method.




回答4:


I solved this problem by testing if it is equal null

if(recyclerView.adapter == null) {recyclerView.adapter = myAdapter}


来源:https://stackoverflow.com/questions/56646711/expected-the-adapter-to-be-fresh-while-restoring-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!