18

I have an activity that starts some other activities for results, so when the result comes back, the activity may or may not have been destroyed and recreated.

I have overridden onSaveInstanceState so as to add the data that needs to be preserved and restored.

When the activity gets destroyed and recreated, onCreate is passed the savedInstanceState bundle; but also onRestoreInstanceState() is called and passed the same bundle.

So where should I put the code that extracts the data from the bundle and restores the state? In onCreate or in onRestoreInstanceState? Is the latter guaranteed to be always called?

Is it possible that onRestoreInstanceState is called without calling onCreate? (e.g. if the activity gets stopped and restarted but not destroyed and recreated)?

matteo
  • 2,934
  • 7
  • 44
  • 59
  • Batter way to keep your code into onRestoreInstanceState() or you can check Bundle args in onCreate() if not null then you can execute the code. When first time onCreate() will called that time Bundle args will be null. – Vishesh Chandra May 05 '14 at 12:35

2 Answers2

13

"Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is NULL"

following link explain pretty clearly about restart activity.

Android Guide

mcd
  • 1,434
  • 15
  • 31
  • Thanks. In this case, what's the use of `savedInstanceState` during onCreate? – Elye Nov 21 '15 at 03:18
  • System Recreate Activity and passes bundle to both method ocreate as well as onRestoreInstanceState Metho you can use both method to restore your state. now i prefer onCreate method because i always start review my as well as others code from oncreate. – mcd Nov 22 '15 at 06:43
  • 1
    @Elye you will likely want to know in onCreate() whether there is a previous state to load. Also, onCreate() will not be called if the Activity was not destroyed. In order to implement a timer, and pause it while the Activity is not on screen, I needed to use onRestoreInstanceState() to adjust the timer accordingly. – Fletcher Johns Dec 06 '15 at 01:42
  • That doesn't answer the question at all. The question is which one to use. – Artem Novikov Sep 24 '16 at 14:26
  • 1
    You can use onRestoreInstanceState – mcd Sep 24 '16 at 14:47
0

The onRestoreInstanceState( ) method is invoked by Android between the onStart( ) and the onResume( ) lifecycle methods.So, in order to restore the state of your activity, simply implement the onRestoreInstanceState( ) method restore activity state.

Rohit
  • 184
  • 5