I have this list:
private ArrayList<Person> people = new ArrayList<>();
And this list is filled with random people. Whenever I turn my screen, the list refreshes and a new list appears. I dont want this to happen.
I have tried to do this with the onSaveInstanceState method like this:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("key", people);
}
but i get the following error at people:
Required type: ArrayList <? extends Parcelable>
Provided: ArrayList<Person>
I am able to fix this error by changing the code to:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("key", (ArrayList<? extends Parcelable>) people);
}
But when I go to the onCreate method where I want to data to load I use this code:
if(savedInstanceState != null)
{
people = savedInstanceState.getParcelableArrayList("key");
}
I get the following error:
Required type: ArrayList <Person>
Provided: ArrayList<Parcelable>
What can I do to make this work? Ive looked everywhere but cannot seem to find the solution. I just need the list to remain the same whenever the screen rotates.
There are a few possible ways to solve the problem:
onSaveInstanceState()by having your classPersonimplement theParcelableinterface. See the Android documentation about how to implementParcelable(you will need to implement a few additional methods to save and restore the data in thePersoninstance.onRetainNonConfigurationInstance()andgetLastNonConfigurationInstance(). You can return your list ofPersonobjects inonRetainNonConfigurationInstance()and then you can retrieve it inonCreate()when yourActivityis recreated (after Android kills it due to the orientation change).static, in which case it will not be reinitialized after Android kills yourActivityand creates a new one. This is not the preferred method, but it is the simplest one.