Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason why "onSaveInstanceState" is not called when "back button" is pressed?

Tags:

android

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?

like image 690
user3302602 Avatar asked Jun 11 '14 09:06

user3302602


People also ask

Is onSaveInstanceState always called?

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.

What happens to an activity when the user presses the back button?

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.

What is the significance of onSaveInstanceState () and onRestoreInstanceState ()?

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.

What is the difference between the onPause () method and the onSaveInstanceState () method?

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.


1 Answers

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.

like image 181
Thomas R. Avatar answered Nov 14 '22 23:11

Thomas R.