How do I save instance of List<Fragments>

134 Views Asked by At

I have a ArrayList of Fragments : ArrayList<Fragment> arrayList;

I want to save the instance of Fragments List when I change orientation on Android Studio. How do I do so?

I tried to do this on OnSaveInstanceState method:

outState.putParcelableArrayList(C_KEY, (ArrayList<? extends Parcelable>) arrayList);

but on my onCreate method:

arrayList = (ArrayList<Fragment>) savedInstanceState.getParcelableArrayList(C_KEY);

does not work because of the error:Inconvertible types; cannot cast 'java.util.ArrayList<android.os.Parcelable>' to 'java.util.ArrayList<androidx.fragment.app.Fragment>

1

There are 1 best solutions below

2
Rahul Agrawal On BEST ANSWER

in your onCreate method your casting is incorrect.

instead of

arrayList = (ArrayList<Fragment>) savedInstanceState.getParcelableArrayList(C_KEY);

put

arrayList = (ArrayList<? extends Parcelable>) savedInstanceState.getParcelableArrayList(C_KEY);

Another option is using ViewModel