简体   繁体   English

关闭 Android 应用程序后如何保存对象?

[英]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.

相关问题 如何停止强制关闭我的应用程序? - How can I stop my application from force closing? 如何保存我的Android应用程序,以便最终用户可以在没有Android SDK的情况下执行它 - How can I save my Android application so that the end-user can execute it without the Android SDK 关闭应用程序后如何保存最后选择的文件夹? - How to save the last selected folder after closing application? 如何加载文件并将其保存在Android中的对象列表中? - How I can load a file and save this in a list of objects in Android? 关闭程序后如何保存对象变量? - How to save object variables after closing my program? 如何停止关闭Java应用程序 - How can I stop the closing of a Java application 如何在我的 Android 应用程序中保存 HashMap? - How can I can save HashMap in my Android app? 用户在我的 android 应用程序中登录或注册后如何更改活动? - How can I change the activity after the user signed in or signed up in my android application? 如何使用Android后退按钮在我的应用中移回而不是关闭我的应用? - How can I use the Android back button to move back within my app instead of closing my app? 当我的Android应用无法连接到服务器时,如何停止强制关闭它? - How can I stop my android app from force closing when it cant connect to my server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM