RyanL
RyanL

Reputation: 15

How do I save instance of List<Fragments>

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>

Upvotes: 1

Views: 157

Answers (1)

Rahul Agrawal
Rahul Agrawal

Reputation: 579

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

Upvotes: 1

Related Questions