Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 'savedInstanceState'?

I am new to Android Development but I have some knowledge of OOP concepts. I am trying to learn Android from Java perspective.

My code

I understand that savedInstanceState inside onCreate() on line 9 is the declaration of Bundle class. On line 10 we are calling the onCreate() method from the super class.

Here is what I don't unterstand: On line 10 we pass savedInstanceState itself as a parameter to the onCreate() method. This doesn't make sense to me as I would expect to pass an object which is of the Bundle type, but instead of that we pass a reference not an object of type Bundle to the method.

like image 686
amitoz Avatar asked May 11 '16 03:05

amitoz


People also ask

What is savedInstanceState?

The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity. Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle.

How do I use savedInstanceState on Android?

The onSaveInstanceState() callback stores data needed to reload the state of a UI controller, such as an activity or a fragment, if the system destroys and later recreates that controller. To learn how to implement saved instance state, see Saving and restoring activity state in the Activity Lifecycle guide.

What does Super onCreate do?

By calling super. onCreate(savedInstanceState); , you tell the Dalvik VM to run your code in addition to the existing code in the onCreate() of the parent class. If you leave out this line, then only your code is run.

Why is savedInstanceState null?

If there is no available instance data, the savedInstanceState will be null.


2 Answers

The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity.

The onCreate() expects to be called with a Bundle as parameter so we pass savedInstanceState.

Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle. If there is no available instance data, the savedInstanceState will be null.

For example, the savedInstanceState will always be null the first time an Activity is started, but may be non-null if an Activity is destroyed during rotation, because onCreate is called each time activity starts or restarts.

Hope it helps

like image 160
Max Avatar answered Sep 20 '22 22:09

Max


When an activity is re-initialized ,then the savedInstance contains the most recent data , specially contains data of the activity's previous initialization part.

Actually, when an activity is killed it saved its states so that when user back to this activity , it can restore its states

like image 41
Atahar Hossain Avatar answered Sep 16 '22 22:09

Atahar Hossain