[英]How can I save an arraylist filled with objects of type person using onSaveInstanceState?
我有這個清單:
private ArrayList<Person> people = new ArrayList<>();
這個名單上到處都是隨機的人。 每當我轉動屏幕時,列表都會刷新並出現一個新列表。 我不希望這種情況發生。
我試圖用這樣的 onSaveInstanceState 方法來做到這一點:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("key", people);
}
但我收到以下錯誤:
Required type: ArrayList <? extends Parcelable>
Provided: ArrayList<Person>
我可以通過將代碼更改為:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("key", (ArrayList<? extends Parcelable>) people);
}
但是,當我將 go 轉到要加載數據的 onCreate 方法時,我使用以下代碼:
if(savedInstanceState != null)
{
people = savedInstanceState.getParcelableArrayList("key");
}
我收到以下錯誤:
Required type: ArrayList <Person>
Provided: ArrayList<Parcelable>
我能做些什么來完成這項工作? 我到處尋找,但似乎找不到解決方案。 每當屏幕旋轉時,我只需要列表保持不變。
有幾種可能的方法可以解決這個問題:
Person
實現Parcelable
接口,將列表保存在onSaveInstanceState()
中。 有關如何實現Parcelable
的信息,請參閱 Android 文檔(您將需要實現一些額外的方法來保存和恢復Person
實例中的數據。onRetainNonConfigurationInstance()
和getLastNonConfigurationInstance()
。 您可以在onRetainNonConfigurationInstance()
中返回您的Person
對象列表,然后您可以在重新創建Activity
時在onCreate()
中檢索它(在 Android 由於方向變化而殺死它之后)。static
,在這種情況下,它不會在 Android 殺死您的Activity
並創建一個新活動后重新初始化。 這不是首選方法,但它是最簡單的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.