取自我的计算器:
@SuppressWarnings("unchecked")
private void loadState() {
ObjectInputStream ois;
try {
ois = new ObjectInputStream(openFileInput(FILE_STATE));
state = ((State) ois.readObject());
ois.close();
ois = new ObjectInputStream(openFileInput(FILE_HISTORY));
historyListAdapter.setItems((List<String>) ois.readObject());
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
state = new State();
} catch (IOException e) {
e.printStackTrace();
state = new State();
} catch (ClassNotFoundException e) {
Toast t = Toast.makeText(this, "Error parsing saved state",
Toast.LENGTH_SHORT);
t.show();
state = new State();
}
setState(state);
}
private void saveState() {
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(openFileOutput(FILE_STATE,
Context.MODE_PRIVATE));
oos.writeObject(state);
oos.close();
oos = new ObjectOutputStream(openFileOutput(FILE_HISTORY,
Context.MODE_PRIVATE));
oos.writeObject(historyListAdapter.getItems());
oos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void onPause() {
saveState();
super.onPause();
}
在 onCreate() 中调用 loadState()。
对我来说工作得很好,我知道不建议在 android 中使用 java 序列化,但我没有遇到任何错误或错误。性能也没有问题。
您当然应该根据您的应用程序调整错误处理。