Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected the adapter to be 'fresh' while restoring state

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 ?

like image 258
SMGhost Avatar asked Jun 18 '19 10:06

SMGhost


Video Answer


3 Answers

it can be fixed by viewPager2.isSaveEnabled = false

like image 169
Yirujiwang Avatar answered Oct 29 '22 23:10

Yirujiwang


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.

like image 25
SMGhost Avatar answered Oct 30 '22 00:10

SMGhost


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);
}
like image 22
Payam Roozbahani Fard Avatar answered Oct 29 '22 22:10

Payam Roozbahani Fard