[英]how can I save objects after closing my Android application?
I am making a small game and I want to save all the variables (objects and basic types) when closing the app to be able to load the saved game later on.我正在制作一个小游戏,我想在关闭应用程序时保存所有变量(对象和基本类型) ,以便以后能够加载保存的游戏。
Here are some of the variables:以下是一些变量:
String playerName;
Duration time;
Item[] inventory=new Item[20]; //enum
int inventoryTotalItems=0;
It is basically the same situation than save variables after quitting application?与退出应用程序后保存变量基本相同的情况? or How can I save an activity state using the save instance state?
或如何使用保存实例 state 保存活动 state? but what I want to save are Objects, so I am not sure I can use the preferences or the Bundle for that.
但我要保存的是对象,所以我不确定我是否可以为此使用首选项或捆绑包。 I also will want to store more than one preference to be able to load different saved games.
我还希望存储多个首选项,以便能够加载不同的已保存游戏。 Can I do this with onPause() and onResume()?
我可以用 onPause() 和 onResume() 做到这一点吗?
Thanks.谢谢。
Add this in your dependencies(in build.gradle file):将此添加到您的依赖项中(在 build.gradle 文件中):
implementation 'com.google.code.gson:gson:2.8.9'
And then you can save objects like this:然后你可以像这样保存对象:
SharedPreferences sp = new getPreferences(MODE_PRIVATE);
Editor pe = sp.edit();
Gson gson = new Gson();
String j = gson.toJson(myObj);
pe.putString("MyObject", j);
pe.commit();
And when you want to access the object later:当您想稍后访问 object 时:
SharedPreferences sp = new getPreferences(MODE_PRIVATE);
Gson gson = new Gson();
String j = sp.getString("MyObject");
MyObject myObj = gson.fromJson(j, MyObject.class);
I think you should save in onPause().我认为你应该保存在 onPause() 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.