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();
}