michael
michael

Reputation: 110630

Where should I restore my android state

From Android Activity API: http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)

It said "the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle)". My question is where should I restored my state? why i can do that in either places?

Thank you.

Upvotes: 0

Views: 482

Answers (2)

JAL
JAL

Reputation: 3319

Consider restoring state in onCreate as the existence of a null bundle is a useful flag for other useful actions in onCreate.

Edit: Looking at my code, another reason to read in the bundle in onCreate is that I update widgets in onCreate. So the state needs to be known in onCreate. It does not matter if the state comes from the bundle or from prefs or from a calling intent. So the pattern looks like

getMyState(); // could be from a bundle or lastNonConfigurationInstance or prefs or a calling intent

someWidget.setYourStateFromInfoInGetState

Upvotes: 1

Aleadam
Aleadam

Reputation: 40401

I will hypothesize here since I never used onSaveInstanceState, but from the docs, you should use the latter. onCreate is called when the activity is started, while onRestoreInstanceState is called after onStart(), that happens after either onCreate() or onRestart().

http://developer.android.com/reference/android/app/Activity.html

protected void onCreate (Bundle savedInstanceState) Since: API Level 1

Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI, calling managedQuery(android.net.Uri, String[], String, String[], String) to retrieve cursors for data being displayed, etc.

protected void onRestoreInstanceState (Bundle savedInstanceState) Since: API Level 1

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. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

protected void onStart () Since: API Level 1

Called after onCreate(Bundle) — or after onRestart() when the activity had been stopped, but is now again being displayed to the user. It will be followed by onResume().

Upvotes: 0

Related Questions