Marlen Schreiner
Marlen Schreiner

Reputation: 836

Lost data on orientation change in fragment

I have a view pager with multi Fragments and my viewPager adapter is:

private class MyPagerAdapter extends FragmentStateAdapter {

    MyPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
        super(fragmentManager, lifecycle);
    }

    @Override
    public Fragment createFragment(int position) {
        Fragment fragment = ScreenFragment.newInstance(position);
        return fragment;
    }

    @Override
    public int getItemCount() {
        return 5;
    }

}

In Fragments, When user changes orientation, I lost all data, and Fragment creates again. I added setRetainInstance(true); to onCreate method of Fragment and set android:configChanges="orientation|screenSize|keyboardHidden" to Activity line in manifest. But my problem still occurs.

Can you help me?

Upvotes: 1

Views: 1064

Answers (2)

Ryan
Ryan

Reputation: 1050

Changing the orientation of a device is considered a configuration change.

Configuration changes will destroy, and then re-create your fragments.

The recommended way to go about this problem is to use a ViewModel. The idea of a ViewModel is that it survives these configuration changes, and when your Fragment is re-created, it will just reconnect to the ViewModel.

Alternatively, you can handle the configuration change yourself. Google does not recommend this option, and is to be used as a last resort.

Upvotes: 2

Zeeshan Ali
Zeeshan Ali

Reputation: 777

You can save data and restore them after rotation.

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) 
   {
    super.onSaveInstanceState(outState, outPersistentState);

    outState.putString("theWord", theWord); // Saving the Variable theWord
    outState.putStringArrayList("fiveDefns", fiveDefns); // Saving the ArrayList 
 fiveDefns
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle 
persistentState) {
    super.onRestoreInstanceState(savedInstanceState, persistentState);

    theWord = savedInstanceState.getString("theWord"); // Restoring theWord
    fiveDefns = savedInstanceState.getStringArrayList("fiveDefns"); //Restoring 
fiveDefns
}

Upvotes: 0

Related Questions