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