2013-04-06 38 views
1

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

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; 
    }} 

错误日志; (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) 
+0

尝试添加检查以查看mediaPlayer是否为空,如果是这样,请再次尝试或通知用户声音无法播放。 – FoamyGuy 2013-04-06 14:51:32

+0

它不在里面oncreate(编辑) – 2013-04-06 14:52:58

+0

什么是60行? – 2013-04-06 14:53:19

回答

6

线60上即mediaplayer.start()的NPE(空指针异常)即将因为它是寻找媒体播放器为空。因此,一个方法是把一个空的选项检查有

if(mediaplayer != null){ 
mediaplayer.start(); 
} 

的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(); 

} 
+0

? – 2013-04-06 15:39:53

+0

是的。里面的按钮onclick()。请接受它是否有效。 – maveroid 2013-04-06 15:48:34

+0

谢谢,它的工作原理 – 2013-04-06 19:48:13