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

前端 未结 2 2012
感动是毒
感动是毒 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();
    }
    
    0 讨论(0)
  • 2021-01-16 15:50

    The onSaveInstanceState will not be called when you press back key to finish it. To save your data all the time you have to use onPause as the code shows:

    @Override
    public void onPause() {
        super.onPause();
        SharedPreferences sp = getSharedPreferences("X", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("lastActivity", HomeActivity.class.getCanonicalName());
    }
    

    Remember to replace HomeActivity with your own class name.BTW, I didn't test the function getCanonicalName, but it should work.

    In your Dispatch Activity, you read the value back and do some action to it.

    0 讨论(0)
提交回复
热议问题