What's onCreate(Bundle savedInstanceState)
Can anyone help me to know about the Bundle savedInstanceState
in onCreate(Bundle savedInstanceState)
I am newbie in Android. I try to understand it from developer.android.com. But I am not able to understand. Can anyone simplify it?
Solution 1:
If you save the state of the application in a bundle (typically non-persistent, dynamic data in onSaveInstanceState
), it can be passed back to onCreate
if the activity needs to be recreated (e.g., orientation change) so that you don't lose this prior information. If no data was supplied, savedInstanceState
is null.
... you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
source
Solution 2:
onCreate(Bundle savedInstanceState)
you will get the Bundle
null when activity get starts first time and it will get in use when activity orientation get changed .......
http://www.gitshah.com/2011/03/how-to-handle-screen-orientation_28.html
Android provides another elegant way of achieving this. To achieve this, we have to override a method called onSaveInstanceState()
. Android platform allows the users to save any instance state. Instance state can be saved in the Bundle. Bundle is passed as argument to the onSaveInstanceState method.
we can load the saved instance state from the Bundle passed as argument to the onCreate
method. We can also load the saved instance state in onRestoreInstanceState
method. But I will leave that for the readers to figure out.