Search code examples
androidandroid-activitysuperclass

Mandatory calling superclass methods of an Android activity?


In the life cycle of an activity, is needed to call to methods of parent class always? .What I mean is:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     
}

public void onStart() {
    super.onStart();

 }



protected void onResume() {
    super.onResume();

}

protected void onPause() {
    super.onPause();


}



protected void onStop() {
    super.onStop();

}

protected void onDestroy() {
    super.onDestroy();

}

protected void onRestart() {
    super.onRestart();

}


public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

}


 public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

}

And do I always have to call the super class method first? For example:

public void onSaveInstanceState(Bundle outState) {
    .....my code.......
    super.onSaveInstanceState(outState);

}


 public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
     .......my code...... 

}

On onSaveInstanceState method it has more sense to write my code first and after to the superclasss method and on onRestoreInstanceState method the opossite?

Thanks


Solution

  • The documentation for the lifecycle methods indicate if calling super.onXXX() is required or not. For some methods this is required, for some it is not.

    For the lifecycle methods which require calling through to super.onXXX(), you can call that method at any time. It can be before or after your code.

    For onSaveInstanceState() and onRestoreInstanceState(), it should also make no difference whether you call super.onXXX() before or after your code. Hopefully, the stuff that you put in the saved instance Bundle does not conflict with the stuff that the Android framework is putting in the Bundle. If it conflicts, you'll have a problem no matter whether you call the super method before or after your code.

    NOTE: The Android framework uses the following keys when putting View and Dialog information in the saved instance Bundle:

     static final String FRAGMENTS_TAG = "android:fragments";
     private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
     private static final String SAVED_DIALOG_IDS_KEY = "android:savedDialogIds";
     private static final String SAVED_DIALOGS_TAG = "android:savedDialogs";
     private static final String SAVED_DIALOG_KEY_PREFIX = "android:dialog_";
     private static final String SAVED_DIALOG_ARGS_KEY_PREFIX = "android:dialog_args_";
    

    so as long as you don't use keys with the same names, you should be good.