Is there a particular reason why "onSaveInstanceState" is not called when the "back button" is pressed? It makes sense to me that view state SHOULD be saved when I press the back button. Is there a particular use-case that the Android developers had in mind that means actually its better that view state is NOT saved when one presses back?
I'm aware that onSaveInstanceState() is not always called when an activity is about to be destroyed. For example, if it is destroyed because the user has pressed the "back" button, the activity state is not preserved.
Once you press the back key the activity's onDestroy() method will be called and the activity will be flushed out of the memory. You will then be required to restart the activity by calling the startActivity() method which will in turn call its onCreate() Method.
The onSaveInstanceState() method allows you to add key/value pairs to the outState of the app. Then the onRestoreInstanceState() method will allow you to retrieve the value and set it back to the variable from which it was originally collected.
From the documentation I understand that onSaveInstanceState() should be called to store only temporary information, and onPause() should be used to store any persistent data.
When performing the back action the activity and fragments will be destroyed. Why should the instance be saved when you don't want to create the activity again (e.g. orientation change).
If you want to saved some data, or better, pass it back to the calling activity/fragment, then you should use the onActivityResult mechanism. For that you have to start the activity with the "start for result" method and set the result in an intent when back button has been pressed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With