Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we call the super class before or after we execute some code

Tags:

android

Android Studio 0.4.6

Hello,

I have a code snippet here. And I have often been confused if super should be the first line of execution or the last. Normally, I make it the first call so that the default properties can be set in the parent class. However, I was looking at some code that does it before. I am just wondering does it make any difference?

  @Override
    protected void onDestroy() {
        mBroadCastMgr.unregisterReceiver(receiver); 
        super.onDestroy();
    }
like image 584
ant2009 Avatar asked Feb 28 '14 09:02

ant2009


3 Answers

As in the docs:

onDestroy() = This callback is called before the activity is destroyed by the system.

Sample Illustration:

/** Called just before the activity is destroyed. */
   @Override
   public void onDestroy() {
      super.onDestroy();
      Log.d(msg, "The onDestroy() event");
   }

Popularly mentioned by user @Cristian (don't know where)-

It really depends on what you want to do in your onDestroy. This is what super.onDestroy does (in that order):

1) Dismiss any dialogs the activity was managing.

2) Close any cursors the activity was managing.

3) Close any open search dialog.

Having said that,

"If the logic you put inside onDestroy has something to do with those three things that android does, then you may have to worry about the order. Otherwise, and in most of the cases, it does not matter."

like image 125
My God Avatar answered Nov 05 '22 16:11

My God


In general when you are creating something your code goes last when you are destroying something your code goes first. It is like in real life imagine adding something to something existing and removing something from something existing

In onDestroy, definitely, place your code first the activity is not valid after super.onDestory

Another interesting situation in onSaveInstanceState you should place your code first because it is super.onSaveInstanceState who does the actual saving (and you thus add what extra you want to save, first)

like image 40
Alexander Kulyakhtin Avatar answered Nov 05 '22 14:11

Alexander Kulyakhtin


If you want to implement cleanup logic safely, you can use next pattern:

@Override
protected void onDestroy() {
    try {
        mBroadCastMgr.unregisterReceiver(receiver);
    } finally {
        super.onDestroy();
    }
}

In general, necessarity of super class call should be checked in all overriden methods using documentation (method javadoc) or super class' source code.

like image 31
zealot Avatar answered Nov 05 '22 16:11

zealot