我有一个复杂的对象,我们可以调用MyComplexObject
。我想将其保存到持久存储中,以便在应用程序被销毁并重新创建后可以检索它。我正在使用这些方法在活动之间传递我的对象(保存在一个活动中并在下一个活动中加载)。我还想在销毁应用程序时保存对象(可能在onStop()
覆盖中)
我可以在活动之间成功加载和保存我的对象但由于某种原因,如果我在手机上销毁应用程序并重新启动它,则总会创建一个新的MyComplexObject,并且无法加载在销毁之前保存的对象!
我的对象包含多个包含多个对象的对象 - 所有对象都实现Serializable
。
有关如何以一种方式保存/加载我的对象的任何想法,这将允许我在应用程序被销毁/重新创建后保留玩家的信息?
即使onDestroy()
和/或onStop()
我收到对象确实已保存的通知!因此,我不确定为什么在重新创建应用程序时无法将其加载回来。
public static MyComplexObject Load(Context context){
try{
FileInputStream fis = context.getApplicationContext().openFileInput("player1.data");
ObjectInputStream is = new ObjectInputStream(fis);
MyComplexObject Game = (MyComplexObject) is.readObject();
is.close();
fis.close();
return Game;
}catch (Exception e){
Log.e("Load", "creating new game - \n" + e.toString());
MyComplexObject NewGame = MyComplexObject();
return NewGame;
}
}
public static void Save(Context context,MyComplexObject 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());
}
}
这是日志:
07-01 14:24:11.824 3304-3304/? E/#Load﹕ creating new world -
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
这是我的onCreate()片段:
MyComplexObject Game;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Game = LoadGame.Load(this); //LoadGame is the class with Load(),Save()
}
答案 0 :(得分:1)
尝试:
public static MyComplexObject Load(Context context){
try{
FileInputStream fis = context.openFileInput("player1.data");
ObjectInputStream is = new ObjectInputStream(fis);
MyComplexObject Game = (MyComplexObject) is.readObject();
is.close();
fis.close();
return Game;
}catch (Exception e){
Log.e("Load", "creating new game - \n" + e.toString());
MyComplexObject NewGame = MyComplexObject();
return NewGame;
}
}
或:
public static MyComplexObject Load(Context context){
try{
FileInputStream fis = context.getApplication().openFileInput("player1.data");
ObjectInputStream is = new ObjectInputStream(fis);
MyComplexObject Game = (MyComplexObject) is.readObject();
is.close();
fis.close();
return Game;
}catch (Exception e){
Log.e("Load", "creating new game - \n" + e.toString());
MyComplexObject NewGame = MyComplexObject();
return NewGame;
}
}