Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using onCreate vs. onRestoreInstanceState

Is there technically any reason why I should use onRestoreInstanceState? Could I not do all the restoration in onCreate by checking if the savedInstanceState bundle is null? What is the primary benefit of using onRestoreInstanceState over doing everything in onCreate?

like image 636
Sean Hill Avatar asked Apr 04 '16 17:04

Sean Hill


People also ask

What is the argument for onCreate function used for?

onCreate(Bundle) is called when the activity first starts up. You can use it to perform one-time initialization such as creating the user interface. onCreate() takes one parameter that is either null or some state information previously saved by the onSaveInstanceState .

How do I use onSaveInstanceState and onRestoreInstanceState on Android?

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 onCreate 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.


1 Answers

onRestoreInstanceState

This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation.

onRestoreInstanceState guarantees you receive a non-null Bundle object also in the lifecycle of activity it's called after onStart But onCreate: you should always check if the Bundle object is null or not to determine the configuration change and as you know it's called before onStart So It's all up to you and depends on your needs.

like image 60
Farshad Tahmasbi Avatar answered Oct 04 '22 15:10

Farshad Tahmasbi