【发布时间】:2014-03-06 16:53:59
【问题描述】:
我有我用计时器记录的时间列表,如果我旋转屏幕,它们会被删除。我尝试了以下代码,但它崩溃了。我认为保存/恢复格式有问题。
ArrayList<Long> timesList = new ArrayList<Long>(); // List of partial times in milliseconds
/** Save state while screen orientation changes */
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putSerializable("PartialTimes", timesList);
}
/** Restore state while screen orientation changes */
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
timesList = (ArrayList<Long>) savedInstanceState.getSerializable("PartialTimes");
}
【问题讨论】:
-
还要确保您不是每次都重新创建
ArrayList。也就是说,您不应该在方向更改时创建new ArrayList<Long> -
我在 onCreated 方法之前创建它(就在导入之后)
-
另外,作为旁注,使您的对象
Parcelable比 Android 上的序列化更快。见stackoverflow.com/questions/3611843/… -
我不知道区别,但我会尝试。不明白为什么要删除列表,需要定义外部变量、数据库还是静态?
标签: java android rotation screen