How to save data and re-open the last used Activity

前端 未结 2 2013
感动是毒
感动是毒 2021-01-16 15:03

I\'ve made the majority of my game\'s mechanics, I now need to be able to:

  1. Save all the data of the current activity and <

2条回答
  •  粉色の甜心
    2021-01-16 15:32

    Why does it happen?

    The Bundle created in onSaveInstanceState is only kept for short-term restarts, e.g. when your activity is recreated due to an orientation change. If your activity stops normally this Bundle is not kept, and thus can't be delivered to onCreate.

    What can I do to fix this?

    Instead of using the instanceState model, save the activity state in SharedPreferences (similar to the lastActivity which you already save). You should save your state in onStop or onPause and restore it in onStart or onResume respectively. In most cases the former is enough and the latter produces only unnecessary overhead.


    @Override
    protected void onStart() {
        super.onStart();
        String saved = sharedPreferences.getString("myKey", null);
        MyPojo pojo;
        if(saved == null){
            pojo = defaultValue;
        }else {
            pojo = new Gson().fromJson(saved, MyPojo.class);
        }
    }
    
    @Override
    protected void onStop() {
        sharedPreferences.edit().putString("myKey", new Gson().toJson(pojo)).apply();
        super.onStop();
    }
    

提交回复
热议问题