Sorry for my poor English.
I have a HashMap<String, Parcelable>
to save some InstanceState
s of a RecyclerView
,and I want to save the HashMap<String, Parcelable>
into a file.
I use the ObjectOutputStream
,it can write into a file,but when I use ObjectInputStream
,it seems that it doesn't have read some useful data,because the state of the RecyclerView
doesn't change to the state that has been saved.
Why this doesn't work?
How can I save and restore InstanceState
of view by "key-value"???
I want to save InstanceState
permanently.
Thank you for your help~
my code:
private HashMap <String, Parcelable> hmRecyclerViewState = new HashMap<String, Parcelable>();
private Parcelable recyclerViewState;
ObjectOutputStream oos;
ObjectInputStream ois;
1.
try {
ois = new ObjectInputStream(new FileInputStream(stateFile));
hmRecyclerViewState = (HashMap<String, Parcelable>)ois.readObject();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.
try {
oos = new ObjectOutputStream(new FileOutputStream(stateFile));
if (hmRecyclerViewState != null)
oos.writeObject(hmRecyclerViewState);
oos.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (oos != null)
oos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
3.
public void saveRecyclerViewState(String tableName) {
recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();
hmRecyclerViewState.put(tableName, recyclerViewState);
}
4.
public void restoreRecyclerViewState(String tableName) {
if ( hmRecyclerViewState.get(tableName) != null) {
recyclerViewState = hmRecyclerViewState.get(tableName);
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
recyclerViewState = null;
}
}