Java Android App MediaPlayer 中的 NullPointerException [英] NullPointerException in Java Android App MediaPlayer

查看:32
本文介绍了Java Android App MediaPlayer 中的 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助,这只是我正在开发的一个简单的 android 应用程序,它的目的是在您每次单击按钮时播放声音......由于运行时错误,按钮速度很快 - NullPointerException!.....我不知道我做错了什么.

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.

这是我的代码

公共类 Main 扩展 Activity 实现 OnClickListener{

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

}

}

推荐答案

它只是一个猜测,但在文档中 这里 你会发现以下内容

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

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

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

不返回 null.

如果 create(Context context, int resid) 失败,我真的不知道如何处理这种情况.但是您必须这样做,因为即使从文档中也很清楚它可能发生.

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

这篇关于Java Android App MediaPlayer 中的 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆