NullPointerException异常在Java中Android应用程序的MediaPlaye

2019-08-02 14:35发布

HELP please this is just a simple android app I am developing, it's meant to play a sound every time you click the button....it works when I click the button at a slow pace, but always crashes if I click the button at a fast pace due to a runtime error - NullPointerException!.....I don't know what I am doing wrong.

THIS IS MY CODE

public class Main extends Activity implements OnClickListener{

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button e = (Button) findViewById(R.id.Button1);
    e.setOnClickListener(this);    

}

public void onClick(View v){

    if(v.getId()==R.id.imageButton1){
    final MediaPlayer i = MediaPlayer.create(Main.this, R.raw.sound);
    i.setOnCompletionListener(new OnCompletionListener() {

        public void onCompletion(MediaPlayer mp) {
            i.release();                    
        }
    });

    i.start();  
    }       

}

}

Answer 1:

它只是一种猜测,但在文档中在这里 ,你会发现下面的

public static MediaPlayer create (Context context, int resid) ......如果创建失败返回一个MediaPlayer对象,或者为null

这意味着你应该确保该线

final MediaPlayer i = MediaPlayer.create(Main.this, R.raw.sound);

不返回null

编辑:

我真的不知道如何处理这种情况,如果create(Context context, int resid)失败。 但是,你必须做的,因为它甚至从文档非常清楚,它可能发生。

可以肯定,这是真正的问题恰恰忽略这种情况,并从处理程序返回。 例如...

public void onClick(View v)
{
    if(v.getId() == R.id.imageButton1)
    {
        final MediaPlayer i = MediaPlayer.create(Main.this, R.raw.sound);

        if (i != null)
        {
            ...

            i.start();
        }
    }       
}


Answer 2:

尝试这种方式....

public class Blah extends Activity implements OnClickListener {
   MediaPlayer mp;

   @Override 
   public void onCreate(Bundle b)
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      Button e = (Button) findViewById(R.id.Button1);

      mp = MediaPlayer.create(R.raw.match);
      mp.setOnCompletionListener(new OnCompletionListener() {

        public void onCompletion(MediaPlayer mp) {
            i.release();                    
        }
    });

      e.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                   mp.seekTo(0);
                       mp.start();

            }
        });
   }


}


Answer 3:

我有同样的问题

我的解决办法是重新编码与LAME MP3编码器的MP3文件

您可以使用此程序: http://www.freac.org/index.php/en/downloads-mainmenu-33

显然Android是相当挑剔的MP3编解码器



文章来源: NullPointerException in Java Android App MediaPlayer