Ferid Movsumov Ferid Movsumov - 1 year ago 51
Android Question

onDestroy() method doesn't work

first I used onDestroy() method as below to make something when my app is closed.

@Override
protected void onDestroy()
{
super.onDestroy();
mediaPlayer.stop();
mediaPlayer2.stop();
}


But it causes a runtime error. I used onStop() method instead and problem was solved. But I wonder why onDestroy doesn't work? Can you explain please.

@Override
protected void onStop()
{
super.onStop();
mediaPlayer.stop();
mediaPlayer2.stop();
}



I was made some changes on my code and now there is no error when I
changed onStop() with onDestroy() I can't understand how but it works.

Answer Source

My guess would be that your mediaPlayer variable was nulled out(destroyed) before arriving in onDestroy. And the error you were seeing was a nullpointerexception.

You could put your stuff back into the ondestroy method and add a simple null test before doing anything with your mediaPlayer :

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

    if (mediaPlayer != null) {
      mediaPlayer.stop();
      mediaPlayer2.stop();
    } 
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download