Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onSaveInstanceState and finish()

Short question: Is it possible to save data using onSaveInstanceState() method, then call finish() on Activity and upon next start of the Activity to get the data back in savedInstanceState? Or does finish() of an Activity mean the data are gone?

If first answer is correct, I have some problem in my implementation because I am getting null in onCreate() although the data was saved. If second answer is correct, I will have to re-think how I connect my Activities together :o)

like image 768
Ellrohir Avatar asked Apr 25 '16 12:04

Ellrohir


People also ask

What is onSaveInstanceState () and onRestoreInstanceState () in activity?

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 purpose of using onSaveInstanceState () here?

Basically, onSaveInstanceState is used for the scenario where Android kills off your activity to reclaim memory. In that scenario, the OS will keep a record of your activity's presence, in case the user returns to it, and it will then pass the Bundle from onSaveInstanceState to your onCreate method.

When onSaveInstanceState () is called?

Choose one: onSaveInstanceState() is called before the onStop() method. onSaveInstanceState() is called before the onResume() method.

What does finish () do in Android?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.


1 Answers

Is it possible to save data using onSaveInstanceState() method, then call finish() on Activity and upon next start of the Activity to get the data back in savedInstanceState?

No.

Or does finish() of an Activity mean the data are gone?

Yes. The saved instance state Bundle is for cases where, from the user's perspective, your activity is still around, but it is being destroyed for technical reasons:

  • Configuration changes (e.g., screen rotation)
  • Process termination (with the user returning to your app fairly quickly)

If finish() is called for other reasons — you calling it directly, user presses BACK, etc. — then the saved instance state is no longer needed and can be discarded.

As a result, the saved instance state Bundle is for transient data that you would like to retain but are comfortable with losing in the face of configuration changes and process termination, such as the contents of a partially-filled-in form.

like image 127
CommonsWare Avatar answered Oct 12 '22 17:10

CommonsWare