【发布时间】:2015-09-21 19:56:46
【问题描述】:
我需要在持久存储中存储一个复杂的自定义对象,以便在我的应用中保存用户的游戏进度。该对象和该对象中的每个对象都实现了Serializable
我称之为使用加载和保存方法在活动之间传递对象。我还调用Save 方法onStop() 在应用程序关闭/销毁时保存对象。它工作正常。
public static Game Load(Context context){
try{
FileInputStream fis = context.openFileInput("player1.data");
ObjectInputStream is = new ObjectInputStream(fis);
Game game = (Game) is.readObject();
is.close();
fis.close();
return game;
}catch (Exception e){
Log.e("#Load", "creating new game - \n" + e.toString());
Game newGame = new Game();
return newGame;
}
}
public static void Save(Context context,Game game){
try{
FileOutputStream fos = context.getApplicationContext().openFileOutput("player1.data", Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(game);
os.close();
fos.close();
}catch (Exception e){
Log.e("#Save", "Failed to save - \n" + e.toString());
}
}
但是,如果应用程序被强制关闭或关闭并销毁,Game 对象就会混乱。重新启动时,应用程序将加载保存在onStop() 的game,但是当用户通过应用程序更改/交互game 对象时,我的应用程序强制关闭并显示“已意外停止”显示消息在手机屏幕上。通过查看日志,我知道当 Game 对象在被强制关闭/销毁后在启动时加载时,Load 方法返回game 而不是newGame,所以不知何故保存/加载过程在 Force Close 之间搞砸了一些事情。
在日志上,我看到了这个:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
因此,我被引导相信使用 Serializable 会发生一些奇怪的事情,或者我错误地写入持久存储。
我的问题:您发现我的代码有什么根本性的问题吗? (请记住,此代码确实有效,只是在强制关闭情况下无效)
有人告诉我考虑使用gson/JSON (?) 来实现我的目的;这种方法会比Serializable 有更好的结果吗?我该如何使用它?
更新:似乎当强制停止发生时,没有调用任何方法——包括onDestroy() 和onStop()。如果是这种情况,那么为什么我的应用程序没有返回 newGame?在强制关闭时查看日志,一条消息说“onSavedInstance not called”,这是什么?
我觉得我应该完全避免Serializable...
onCreate sn-p
Game game;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
game = LoadGame.Load(this); //LoadGame is the class which contains Save,Load methods
@Override
protected void onStop() {
LoadGame.Save(this,game);
super.onStop();
}
【问题讨论】:
-
您能否展示您的
onStop方法以及onCreate(或者您从哪里调用Load)?似乎错误发生在您提供的代码范围之外。 -
@Khalos 已添加
标签: java android serialization persistent-storage