-2

// Necessary libraries are imported.

public class MainActivity extends AppCompatActivity {
    MediaPlayer mPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void playAudio(View view) {
        mPlayer.create(this, R.raw.hahah);
        mPlayer.start();
    }

    public void pauseAudio(View view) {
        mPlayer.pause();
    }

}

This is my MainActivity. The app crashes as soon as I press play or pause button. This app works when I remove both the buttons and allow it to start playing automatically in onCreate method.

MJM
  • 5,119
  • 5
  • 27
  • 53
Abhay V Ashokan
  • 320
  • 3
  • 9

3 Answers3

3

You forgot

MediaPlayer mPlayer =new MediaPlayer();  

in onCreate method

Urvish Jani
  • 104
  • 1
  • 4
0

You must initialize class before using it. Object is not created for the mplayer.

Initialize it in the onCreate() method

MediaPlayer mPlayer =new MediaPlayer(); 
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Magudesh
  • 419
  • 5
  • 13
0

Well, whenever you define a variable but don't assign value to it, it will crash the app. Here you are creating a MediaPlayer but not assigning it. You should add this code in your onCreate() method:

MediaPlayer mMediaPlayer = new MediaPlayer();

This will create a new instance of the MediaPlayer object and you can reuse the functions of that class.

Gourav
  • 2,746
  • 5
  • 28
  • 45