I\'ve made the majority of my game\'s mechanics, I now need to be able to:
Save all the data of the current activity and <
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();
}
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.