2014-02-09 44 views
2

我有一个计时器列表,如果我旋转他们被删除的屏幕。我试过下面的代码,但它崩溃了。我认为保存/恢复格式存在问题。Android保存并恢复ArrayList <Long>屏幕更改

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"); 

} 
+0

还要确保你没有重新创建'ArrayList'每次。也就是说,你不应该在方向改变时创建一个新的ArrayList

+0

我在onCreated方法之前创建它(刚刚导入之后) – avafab

+0

另外,作为一个附注,使你的对象'Parcelable'比Android上的序列化更快。请参阅http://stackoverflow.com/questions/3611843/is-using-serializable-in-android-bad –

回答

-1

我终于放上这行的清单,主要活动中,以这种方式保持列表值即使方向改变解决了这个问题。

android:configChanges="keyboardHidden|orientation" 
+1

这不是一个解决方案 - 它最好是一种解决方法。了解为什么android默认重新创建您的定位更改活动的原因。了解您的活动可以在任何时候销毁和重新创建,无论方向如何。掌握这些知识后,你将会更好地了解并解决你的问题。 –

+0

嗨格雷格,让我明白这一点。 – avafab

1

只是用于保存

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

而对于retrive

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