媒体播放器NullPointerException?

Erd*_*klı 1 android nullpointerexception android-mediaplayer

我在铃声应用程序(mp3声音)中使用mediaplayer.它工作正常,但我看到谷歌播放开发者控制台(对于一些用户)的错误报告,我找不到我的设备上的错误,谢谢

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    soundname= new String[]  {"Sound1","Sound2","Sound3","Sound4","Sound5","Sound6"}; 
    soundfile= new int[] {R.raw.sound1,R.raw.sound2,R.raw.sound3,R.raw.sound4,R.raw.sound5,R.raw.sound6};

    this.setContentView(R.layout.single_list_item_view);

    TextView txtProduct = (TextView) findViewById(R.id.product_label);
    Intent intent = getIntent();
    int position = intent.getExtras().getInt("position");

    txtProduct.setText(soundname[position]);
    stopPlaying();  
    mediaPlayer = MediaPlayer.create(this, soundfile[position]); 

    Button btnplay= (Button) findViewById(R.id.btnoynat);
    btnplay.setOnClickListener(new View.OnClickListener(){

        public void onClick(View arg0) { 
                mediaPlayer.start();         
        }
        });
}

private void stopPlaying() {
    if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
  }}
Run Code Online (Sandbox Code Playgroud)

错误日志; (mediaPlayer.start(); - > SingleListItem.java:60)

java.lang.NullPointerException
at com.zilsesleri.SingleListItem$1.onClick(SingleListItem.java:60)  
at android.view.View.performClick(View.java:2538)
at android.view.View$PerformClick.run(View.java:9152)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3693)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
at dalvik.system.NativeStart.main(Native Method)
Run Code Online (Sandbox Code Playgroud)

mav*_*oid 9

在第60行,即mediaplayer.start()NPE(空指针异常)即将到来,因为它发现mediaplayer为null.因此,一种方法是在那里进行空选项检查

if(mediaplayer != null){
mediaplayer.start();
}
Run Code Online (Sandbox Code Playgroud)

NPE即将到来,因为在原始声音文件中创建媒体播放器在某些设备上失败了.

此外,您需要在MediaPlayer的onCompletionListener中停止()和释放()媒体播放器,以便它不会因为链接中提到的清理资源失败而失败: - MediaPlayer-> create

EG->

MediaPlayer mediaplayer = MediaPlayer.create(this, R.raw.sound1);        
if(mediaplayer == null) {            
    Log.v(TAG, "Create() on MediaPlayer failed.");       
} else {
    mediaplayer.setOnCompletionListener(new OnCompletionListener() {

    @Override
      public void onCompletion(MediaPlayer mediaplayer) {
          mediaplayer.stop();
          mediaplayer.release();
      }
    });
    mediaplayer.start();

}
Run Code Online (Sandbox Code Playgroud)