-1

Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference

Below is the code -

package com.example.zhengli.mediaplayerdemo;

import android.media.MediaPlayer;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Button mb1;

    private MediaPlayer mpplayer;


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

        mb1=(Button)findViewById(R.id.play);
        mb1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mpplayer=new MediaPlayer();
                mpplayer=MediaPlayer.create(MainActivity.this,R.raw.mp);
                mpplayer.start();
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mpplayer.isPlaying()){
            mpplayer.stop();
        }
        mpplayer.release();//释放资源
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
zheng zheng
  • 11
  • 1
  • 1

1 Answers1

0

According to developers doc for mediaplayer.create

MediaPlayer.create (Context context,int resid) returns a MediaPlayer object, or null if creation failed .

Check your media file

and you may rise null pointer exception in your onDestory use this instead

if(mpplayer!-null){

     if(mpplayer.isPlaying()){
            mpplayer.stop();
        }
        mpplayer.release();

}
Amir Hossein Mirzaei
  • 2,325
  • 1
  • 9
  • 17