对不起我的英语不好。
我有 aHashMap<String, Parcelable>
来保存一些InstanceState
a RecyclerView
,我想将 a 保存HashMap<String, Parcelable>
到一个文件中。
我用的是ObjectOutputStream
,它可以写入一个文件,但是当我使用时ObjectInputStream
,它似乎没有读取一些有用的数据,因为它的状态RecyclerView
并没有改变到已经保存的状态。
为什么这不起作用?
如何通过“键值”InstanceState
保存和恢复视图???
我想InstanceState
永久保存。
谢谢你的帮助~
我的代码:
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;
}
}