2

我有一個recyclerView包含一個類的對象的列表。目前,當我關閉我的應用程序時,recyclerView中的所有列表都會丟失,重新啓動應用程序後,recyclerView將不顯示任何內容(無列表)。保存RecyclerView列表狀態

甚至在我關閉並銷燬之後,我應該如何保留該清單?

public class Info { 
public String pName; 
public String pContact; 
public Character pGender; 
public int pID; 
public String tDateTime; // today's date and time 
} 

我將這個類的對象存儲在arraylist中以填充我的recyclerview適配器。

+0

您可以使用本地數據庫來存儲此鏈接的數據http://www.androidauthority.com/how-to-store-data-locally-in-android-app-717190/ –

+0

您在列表中顯示的數據?你能分享你的來源嗎? – JavadKhan

+0

你如何填寫數據?無論如何,我需要這個來源。如果您手動填寫數據,按EditText輸入,那麼您應該使用sqlite數據庫。 – JavadKhan

回答

0

保存狀態:

protected void onSaveInstanceState(Bundle state) { 
    super.onSaveInstanceState(state); 

    // Save list state 
    mListState = mLayoutManager.onSaveInstanceState(); 
    state.putParcelable(LIST_STATE_KEY, mListState); 
} 

恢復狀態:

protected void onRestoreInstanceState(Bundle state) { 
    super.onRestoreInstanceState(state); 

    // Retrieve list state and list/item positions 
    if(state != null) 
     mListState = state.getParcelable(LIST_STATE_KEY); 
} 

然後更新佈局管理:在活動

@Override 
protected void onResume() { 
    super.onResume(); 

    if (mListState != null) { 
     mLayoutManager.onRestoreInstanceState(mListState); 
    } 
} 
+0

我試過這個,但沒有奏效。關閉應用程序後,RecyclerView仍然爲空。 –

+0

分享您的日誌錯誤和源代碼。 –

1

覆蓋的onSaveInstanceState和保存模型的狀態,而不是佈局管理器的狀態。如果視圖顯示任何數據,那麼您肯定有數據模型。

由於非常小,您只需要記住當前模型中的物品數量。這是如果模型能夠從某處獲取所需項目的內容。如果不是,或者需要太長的時間,州還需要包括正在顯示的項目。像

@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putSerializable("d.list.data", adapter.getState()); 
} 

而且,一些地方必須恢復狀態:

if (savedInstanceState != null) { 
    adapter.setState(savedInstanceState.getSerializable("d.list.data")); 
} 

Here是保存和與RecyclerView使用的模型應用狀態類的代碼。

+0

Llink is break :( – ramaral

+1

現在應該修復鏈接。感謝您的報告。 – h22