ClassCastException occurs on onRestoreInstanceState

ClassCastException occurs randomly to restore Vector in onRestoreInstanceState (). Usually the recovery vector is completed well, but sometimes an exception occurs.

I think this happens when activity goes to the background and is destroyed, but I'm not sure.

Any ideas? Thanks.

Stack<LocationInfo> mLocationInfoVector; @Override protected void onSaveInstanceState(Bundle outState) { outState.putSerializable("locationInfos", mLocationInfoVector); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { if (savedInstanceState.getSerializable("locationInfos") != null) { @SuppressWarnings("unchecked") mLocationInfoVector= (Stack<LocationInfo>) savedInstanceState.getSerializable("locationInfos"); } super.onRestoreInstanceState(savedInstanceState); } 

ADDED:

I forgot to attach an exception log. it

 java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Stack 
+7
source share
2 answers

I use the following code to restore Vector:

 objects = new Vector<Object>((Collection<Object>) state.getSerializable(EXTRA_OBJECTS)); 

It prevents java.lang.ClassCastException and maintains the order of the elements.

To restore the stack, you can use the following code:

 stack = new Stack<Object>(); stack.addAll((Collection<Object>) state.getSerializable(EXTRA_STACK)); 

It works due to the fact that Vector, Stack, ArrayList extend Collection, and you can make your serialized object in Collection and go to the Stack method or Vector addAll ().

+5
source

This usually occurs when activity has been disrupted due to memory pressure. The packet passed to onRestoreInstanceState apparently saves an instance of the base class ( ArrayList in this case).

You may be able to reproduce the problem by changing the developer options:

  • Go to Settings | Developer Options
  • Check the box "Do not perform actions"

Now your activity will be destroyed immediately after its release. Starting this operation, clicking the Home button, and then returning to your application should raise a ClassCastException .

Meanwhile, Ted Hopp's suggestion to use

 if (saved instanceof Stack) { .... } 

app crash should be avoided.

+4
source

All Articles