Why does super.onDestroy() in java Android goes on top in destructors?

JavaAndroidDestroy

Java Problem Overview


According to which logic does super.onDestroy(); in destructors goes on top? For example:

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

and not:

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

Like in c++, obj-c, pascal, etc?

Java Solutions


Solution 1 - Java

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

  • Dismiss any dialogs the activity was managing.
  • Close any cursors the activity was managing.
  • Close any open search dialog

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.

Solution 2 - Java

In the ThreadSample.zip on the Reporting Work Status training, there is a comment in onDestroy()

public void onDestroy() {
    ...
    // Must always call the super method at the end.
    super.onDestroy();
}

So perhaps when using Broadcast Receivers, the super must go at the end.

Solution 3 - Java

Since we are extending from the base android classes, it is always good approach to let the parent class create and initialize itself first during the creation and let the child uninitialize and free the resource first during shutdown/stopping the components. This is the recommended approach to be followed. however, it entirely depends on the use cases and scenarios.

public void onCreate(Bundle bundle){
   super.onCreate(bundle);
   //perform child class initializations.
}

public void onDestroy(){
   //perform uninitialization and free resource
    super.onDestroy();
}

Solution 4 - Java

What's your question? You can do it either way, it depends if you want your superclass's onDestroy() called before yours. Usually I don't think it matters in android.

Also, onDestroy() isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state. So your instance is still alive and very well* after the superclass's onDestroy() runs and returns.

*Most likely, android is free to kill the activity at any time, but you can assume it's still there.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVassilisView Question on Stackoverflow
Solution 1 - JavaCristianView Answer on Stackoverflow
Solution 2 - JavaZorflingView Answer on Stackoverflow
Solution 3 - JavasivaView Answer on Stackoverflow
Solution 4 - JavaFalmarriView Answer on Stackoverflow