我有一个非常奇怪的错误,我无法弄清楚发生了什么。在我的代码中,我通过 SoundsClass 使用媒体播放器,如下所示:
public class SoundsClass {
private int sound;
private Context mContext;
public SoundsClass(int sound, Context mContext) {
this.sound=sound;
this.mContext=mContext;
}
public void clickOnAndroid() {
switch(this.sound) {
case R.raw.sound1:
MediaPlayer mediaPlayer = MediaPlayer.create(mContext, R.raw.sound1);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
break;
case R.raw.sound2:
mediaPlayer = MediaPlayer.create(mContext, R.raw.sound2);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
break;
case R.raw.sound3:
mediaPlayer = MediaPlayer.create(mContext, R.raw.sound3);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
break;
}
}
}
所以,我在我的主要活动中使用这个类,如下所示:
new SoundsClass(R.raw.sound1, getBaseContext()).clickOnAndroid();
在此活动的 2 个地方它工作正常,但第三个给出 NullPointerException,由 SoundsClass 中的行指向:
mediaPlayer.start();
知道为什么吗?我是否以错误的方式使用 MediaPlayer?
Logcat 是:
java.lang.NullPointerException
at com.testingapp.app.SoundsClass.clickOnAndroid(SoundsClass.java:42)
at com.testingapp.app.MainActivity$2.onClick(MainActivity.java:147)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
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:3683)
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:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
也许我应该补充一点,我经常调用这个 SoundsClass,中间没有或几乎没有停顿。有时我会得到:
bufferCount is to small and increased to 12.