当我尝试多次单击按钮时,我遇到了此错误。 以下是logcat中的错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.huiiy.myapplication, PID: 3933
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.example.huiiy.myapplication.Activity9$13.onClick(Activity9.java:288)
at android.view.View.performClick(View.java:5712)
at android.view.View$PerformClick.run(View.java:22514)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6141)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
下面是我的应用程序的编码:
iv_33.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MediaPlayer ivbsound = new MediaPlayer();
ivbsound = MediaPlayer.create(Activity9.this,R.raw.ivbutton);
// MediaPlayer ivbsound = MediaPlayer.create(Activity9.this,R.raw.ivbutton);
ivbsound.start();
int theCard = Integer.parseInt((String) view.getTag());
doStuff(iv_33, theCard);
}
});
答案 0 :(得分:2)
您好,尝试用其他音频文件创建播放器。 也许ivbutton文件已损坏
[更新]
如果您要重用它,请声明此声音播放器的惰性属性,并在每次单击播放时将其
class MyActivity extends AppCompatActivity {
private MediaPlayer soundPlayer = null;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
soundPlayer = MediaPlayer.create(this, R.raw.ivbutton);
iv_33.setOnClickListener(view -> {
soundPlayer.start();
int theCard = Integer.parseInt((String) view.getTag());
doStuff(iv_33, theCard);
});
}
}
答案 1 :(得分:1)
这意味着创建MediaPlayer失败(也许您有关于它的警告/调试消息)。 创建新的MediaPlayer然后用新的MediaPlayer代替它是没有用的。
检查R.raw.ivbutton是否存在并与良好的媒体相对应(可以运行)。
个人而言,这就是我的工作方式:
File mediaFile = obj.getFile();
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaFile.setReadable(true); // be sure that the program have access to the media content
// this try/catch is to support multiple Android version
try {
mediaPlayer.setDataSource(mediaFile.getAbsolutePath());
} catch (Exception e) {
mediaPlayer.setDataSource(context, Uri.fromFile(mediaFile));
}
mediaPlayer.prepare(); // prepare it, after you can change volume ...
} catch (Exception e){
e.printStackTrace();
}
mediaPlayer.start(); // finally start the media
答案 2 :(得分:1)
请确保您尝试播放的声音文件格式受here中的一项检查清单支持。因为在不支持文件的情况下MediaPlayer.create返回null,这会导致空指针异常。另外我建议在调用ivbsound.start()之前检查if(ivbsound!= null);