Search code examples
androidonpausebackground-music

Android Adding music to MainActivity app crashes after exiting?


I am making an app in which I have a splash screen, and a menu page which has two buttons. I have added background music to the menu page. When I exit from the app the music doesn't stop. I tried onPause() and onStop() even onDestroy() methods but after adding them when i exit the app the app crashes showing "Unfortunately appname has stopped working" Here is my code please help me out as iam new to this. package com.example.appname;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;


public class MainActivity extends Activity {
MediaPlayer backgroundsong;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
     WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_main);
    MediaPlayer backgroundsong= MediaPlayer.create(MainActivity.this, R.raw.penguinshort);
    backgroundsong.start();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
   backgroundsong.release();
}

}


Solution

  • Hey you create a local variable in the function so your global variable is null...

    When you define a same-name local variable in some function, the usage of the variable name in this function points to the local one, not the global one.

    MediaPlayer backgroundsong=MediaPlayer.create(MainActivity.this, R.raw.penguinshort);
    backgroundsong.start();
    

    Change to

    backgroundsong=MediaPlayer.create(MainActivity.this, R.raw.penguinshort);
    backgroundsong.start();