Search code examples
javaandroidclose-application

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

Thanks.


Solution

  • Add this in your dependencies(in build.gradle file):

    implementation 'com.google.code.gson:gson:2.8.9'
    

    And then you can save objects like this:

    SharedPreferences sp = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor pe = sp.edit();
    Gson gson = new Gson();
    String j = gson.toJson(myObj);
    pe.putString("MyObject", j);
    pe.apply();
    

    And when you want to access the object later:

    SharedPreferences sp = getPreferences(MODE_PRIVATE);
    Gson gson = new Gson();
    String j = sp.getString("MyObject", null);
    MyObject myObj = gson.fromJson(j, MyObject.class);
    

    I think you should save in onPause().