我正在尝试在用户旋转屏幕时恢复RecyclerView数据。 这是我的代码: 的 __ MESSAGE_Item.java:
public class __MESSAGE_Item implements Serializable {
private String title, writer, message, index, parent;
int time, level;
public __MESSAGE_Item() {
}
public __MESSAGE_Item(String title, int time, String writer, String message, String index, String parent, int level) {
this.title = title;
this.time = time;
this.writer = writer;
this.message = message;
this.index = index;
this.parent = parent;
this.level = level;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public String getParent()
{
return parent;
}
public void setParent(String parent)
{
this.parent = "בתגובה להודעה " + parent;
}
public int getLevel()
{
return level;
}
public void setLevel(int level)
{
this.level = level;
}
}
MainActivity.java:
private ArrayList<__MESSAGE_Item> MessageList = new ArrayList<__MESSAGE_Item>();
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LVM = (RecyclerView) findViewById(R.id.LVM);
adapter = new __MESSAGE_ListAdapter(MessageList, getApplicationContext());
if (savedInstanceState == null) {
//Call The AsyncTask
new GetAllMessages().execute();
}
.....
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable("LVMData", MessageList);
super.onSaveInstanceState(savedInstanceState);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
MessageList = (ArrayList<__MESSAGE_Item>) savedInstanceState.getSerializable("LVMData");
adapter.notifyDataSetChanged();
}
}
当我尝试恢复时,数据传递良好,但RecyclerView为空。 我做错了什么?
答案 0 :(得分:1)
onRestoreInstanceState
,因此在旋转屏幕时可能不会调用它。
您需要在else
方法中添加onCreate
条件,并在其中添加内容。
答案 1 :(得分:0)
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable("LVMData", MessageList);
super.onSaveInstanceState(savedInstanceState);
}
这应该是
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putSerializable("LVMData", MessageList);
}