2014-02-09 49 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"));