我需要将复杂的自定义对象存储在永久存储器中,以便将用户的游戏进度保存在我的应用程序中。该对象和该对象中的每个对象都实现了Serializable将可序列化对象保存在永久存储器中(android)
我称之为使用加载和保存方法在活动之间传递对象。我还打电话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,或我错误地写入持久性存储。
我的问题:你是否发现我的代码有什么根本错误? (请记住,这段代码确实有效,但在Force Close情况下它不起作用)
我被告知要使用gson/JSON(?)作为我的目的;这种方法会比Serializable有更好的结果,我该如何使用它?
更新:似乎发生强制停止时,不会调用任何方法 - 包括onDestroy()和onStop()。如果是这样,那么为什么我的应用程序不返回newGame?在强制关闭时查看日志,这条消息提到了“onSavedInstance没有调用”的内容,这是什么?
我得到我应避免Serializable的感觉完全...
的onCreate片断
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();
}
+0
你可以显示你的'onStop'方法以及'onCreate'(或者你正在调用'Load')吗?看来错误发生在您提供的代码范围之外。 –
+0
@Khalos它已被添加 –