ClassCastException随机发生以恢复onRestoreInstanceState()中的Vector.
通常恢复向量很好,但有时会发生异常.
通常恢复向量很好,但有时会发生异常.
我认为它发生在活动进入后台并被破坏但我不确定.
有任何想法吗?谢谢.
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); }
添加:
我忘了附上异常日志.
那是
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Stack
解决方法
我使用下一个代码来恢复Vector:
objects = new Vector<Object>((Collection<Object>) state.getSerializable(EXTRA_OBJECTS));
它会阻止java.lang.ClassCastException并保存元素顺序.
要恢复Stack,您可以使用下一个代码:
stack = new Stack<Object>(); stack.addAll((Collection<Object>) state.getSerializable(EXTRA_STACK));
它的工作原理是Vector,Stack,ArrayList都在扩展Collection,你可以将你的序列化对象转换为Collection并传递给Stack或Vector addAll()方法.