媒体播放器空指针异常

时间:2012-07-09 18:03:17

标签: android pointers null media

我有一个非常奇怪的错误,我无法弄清楚发生了什么。在我的代码中,我通过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.

2 个答案:

答案 0 :(得分:3)

http://developer.android.com/reference/android/media/MediaPlayer.html#create(android.content.Context,%20android.net.Uri,%20android.view.SurfaceHolder

如果创建失败,MediaPlayer.create调用将返回null。如果它找不到指定的媒体或媒体格式无效,则可能是这样。

答案 1 :(得分:3)

这对我有用:

mediaPlayer = MediaPlayer.create(mContext, R.raw.sound1);
while(mediaPlayer == null) {
      mediaPlayer = MediaPlayer.create(mContext, R.raw.sound1);
}