【问题标题】:Android save and restore ArrayList <Long> while screen changesAndroid在屏幕更改时保存和恢复ArrayList <Long>
【发布时间】: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&lt;Long&gt;
  • 我在 onCreated 方法之前创建它(就在导入之后)
  • 另外,作为旁注,使您的对象Parcelable 比 Android 上的序列化更快。见stackoverflow.com/questions/3611843/…
  • 我不知道区别,但我会尝试。不明白为什么要删除列表,需要定义外部变量、数据库还是静态?

标签: java android rotation screen


【解决方案1】:

只用于保存

Long[] array = new Long[list.size()];
array = list.toArray(array);
savedInstanceState.putLongArray("PartialTimes", array);

为了检索

ArrayList<Long> list = Arrays.asList(savedInstanceState.getLongArray("PartialTimes"));

【讨论】:

  • 这完全是编译器错误,Android工作室说“需要long[]但找到java.lang.Long[]
【解决方案2】:

我终于解决了这个问题,将这一行放在清单中,在主要活动中,这样即使方向发生变化,它也会保留列表值。

android:configChanges="keyboardHidden|orientation"

【讨论】:

  • 这不是一个解决方案——它充其量是一种解决方法。了解 android 默认在方向更改时重新创建活动的原因。了解您的活动可以随时销毁和重新创建,无论方向如何。有了这些知识,您将能够更好地理解和解决您的问题。
猜你喜欢
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 2016-12-11
相关资源
最近更新 更多