Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the savedInstanceState bundle actually used?

Does anyone know of an exhaustive list of when the savedInstanceState bundle will be used in an activity?

I know it's used when the device orientation changes. However, it doesn't seem to be used when the user force closes the app from the Android settings, but this might be due to something in my code.

What other cases are there?

To be clear, by "used" I mean when onCreate() is called, the savedInstanceState bundle is not null and contains the data I passed into it the last time onSaveInstanceState() was called.

like image 690
howettl Avatar asked Mar 23 '12 21:03

howettl


People also ask

What is the use of bundle savedInstanceState in Android?

What is the savedInstanceState Bundle? 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.

Under which circumstances does the onCreate () method in your activity receive a bundle with data in it that is the bundle is not null )?

Under which circumstances does the onCreate() method in your activity receive a Bundle with data in it (that is, the Bundle is not null )? The activity is restarted after the device is rotated.

What is the role of the bundle passed to an activity's onCreate method?

onCreate(Bundle savedInstanceState) Function in Android: Basically Bundle class is used to stored the data of activity whenever above condition occur in app. onCreate() is not required for apps. But the reason it is used in app is because that method is the best place to put initialization code.

What is the use of onSaveInstanceState?

onSaveInstanceState() is a method used to store data before pausing the activity.


1 Answers

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.

like image 133
triad Avatar answered Sep 18 '22 16:09

triad