gpt4 book ai didi

java - 为什么我的对象不保存到持久存储?

转载 作者:行者123 更新时间:2023-12-01 11:21:32 25 4
gpt4 key购买 nike

我有一个复杂的对象,我们可以将其称为MyComplexObject。我想将其保存到持久存储中,以便在应用程序被销毁并重新创建后可以检索它。我使用这些方法在 Activity 之间传递对象(在一个 Activity 中保存并在下一个 Activity 中加载)。我还想在应用程序被销毁时保存对象(可能在 onStop() 覆盖中)我可以在 Activity 之间成功加载和保存我的对象,但由于某种原因,如果我销毁手机上的应用程序并重新启动它,总是会创建一个新的 MyComplexObject,并且无法加载销毁之前保存的对象!

我的对象包含多个对象,这些对象又包含多个对象 - 所有这些对象都实现了Serialized

关于如何能够以允许我在应用程序被销毁/重新创建后保留玩家信息的方式保存/加载我的对象,有什么想法吗?

即使在 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() 代码 fragment :

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()
}

最佳答案

尝试:

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;
}
}

关于java - 为什么我的对象不保存到持久存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31169334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com