NullPointerException in Java Android App MediaPlayer

后端 未结 3 1728
北荒
北荒 2021-01-26 07:29

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, bu

3条回答
  •  伪装坚强ぢ
    2021-01-26 07:51

    Its only a guess but in the documentation here you will find the following

    public static MediaPlayer create (Context context, int resid) ... Returns a MediaPlayer object, or null if creation failed

    This means you should make sure that the line

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

    does not return a null.

    Edit:

    Im really not sure how to handle the situation if create(Context context, int resid) is failing. But you have to do, because it is even from the documentation very clear that it can happen.

    To be sure this is really the problem just ignore this case and return from your handler. For example...

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

提交回复
热议问题