Reputation: 37
When I am going through sample code of apps I came across onsaveInstanceState
method many times. Why do we use it generally?
Upvotes: 3
Views: 5012
Reputation: 6282
It's used when the Activity is forcefully terminated by the OS (ex: when your Activity is in the background and another task needs resources). When this happens, onSaveInstanceState(Bundle outstate) will be called and it's up to your app to add any state data you want to save in outstate.
When the user resumes your Activity,
onCreate(Bundle savedInstanceState)
gets called and savedInstanceState will be non-null if your Activity was terminated in a scenario described above. Your app can then grab the data from savedInstanceState and regenerate your Activity's state to how it was when the user last saw it.
Basically in onCreate, when savedInstanceState is null, then it means this is a 'fresh' launch of your Activity. And when it's non-null (if your app saved the data in onSaveInstanceState(...), it means the Activity state needs to be recreated.
Edit: Also, please search before ask. What is 'savedInstanceState'?
Upvotes: 1
Reputation: 67209
Android components such as Fragments and Activities have a lifecycle. These components can be stopped, started, or completely taken out of memory for any of a number of reasons. onSaveInstanceState()
and other such lifecycle callbacks give you an opportunity to save any application state that you want to restore when the user returns to your application.
For example, let's say you have a simple text field in your application. Consider this workflow:
In this case, you likely want to keep the user's input around so they don't have to type it in again. This is a great use of the component's saved instance state.
You might ask "why would I need to restore that state, isn't it already there?" The short answer is "it depends." If the user has only left your app for a brief period of time and the phone has sufficient RAM, your components may still be in memory and you don't need to worry. However, the Android OS may need to take your application out of memory to make room for the other application. In this case, your application will be given the opportunity (via onSaveInstanceState()
and friends) to persist any state should the user return to your application.
Note that many View
s already do this, EditText
included. But you can imagine many similar use cases where there is some sort of application state that you want to save should the user leave your app.
Upvotes: 5