chr*_*ris 8 android bundle serializable
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);
}
Run Code Online (Sandbox Code Playgroud)
添加:
我忘了附上异常日志.那是
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Stack
Run Code Online (Sandbox Code Playgroud)
这通常发生在活动因内存压力而被破坏时.传递给onRestoreInstanceState的bundle似乎保留了基类的实例(ArrayList在本例中).
您可以通过调整开发人员选项来重现该问题:
现在,您的活动将在您离开后立即销毁.启动相关活动,按"主页"按钮,然后切换回应用程序应触发ClassCastException.
与此同时,Ted Hopp建议使用
if (saved instanceof Stack) {
....
}
Run Code Online (Sandbox Code Playgroud)
应避免崩溃应用程序.
我使用下一个代码来恢复Vector:
objects = new Vector<Object>((Collection<Object>) state.getSerializable(EXTRA_OBJECTS));
Run Code Online (Sandbox Code Playgroud)
它会阻止java.lang.ClassCastException并保存元素顺序.
要恢复Stack,您可以使用下一个代码:
stack = new Stack<Object>();
stack.addAll((Collection<Object>) state.getSerializable(EXTRA_STACK));
Run Code Online (Sandbox Code Playgroud)
它的工作原理是Vector,Stack,ArrayList都在扩展Collection,你可以将你的序列化对象转换为Collection并传递给Stack或Vector addAll()方法.
| 归档时间: |
|
| 查看次数: |
1275 次 |
| 最近记录: |