Android的 - 播放声音的按钮,点击 - 空指针异常 [英] Android - play sound on button click - Null pointer exception

查看:626
本文介绍了Android的 - 播放声音的按钮,点击 - 空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上的一个按钮的点击播放声音文件。声音是只有1秒长。它扮演好第几次我按一下按钮,但经过一段时间它给了一个 NullPointerException异常。这里的code:

 按钮[I] .setOnClickListener(新OnClickListener(){
    公共无效的onClick(视图查看){
        MP = MediaPlayer.create(Test.this,R.raw.mysound);
        mp.start();
    }
});
 

和这里的异常:

  07-29 23:07:27.690:ERROR / AndroidRuntime(10542):未捕获的处理程序:螺纹主力退出,由于未捕获的异常
07-29 23:07:27.710:ERROR / AndroidRuntime(10542):显示java.lang.NullPointerException
07-29 23:07:27.710:ERROR / AndroidRuntime(10542):在com.example.mypackage.Test $ 3.onClick(Test.java:270)
 

你的答案

解决方案

谢谢你!鸭preciate了!

下面就是我终于设法得到它的工作:

 按钮[I] .setOnClickListener(新OnClickListener(){
                公共无效的onClick(视图查看){

                    MP = MediaPlayer.create(Test.this,R.raw.mysound);
                    mp.setOnCompletionListener(新OnCompletionListener(){

                        @覆盖
                        公共无效onCompletion(MediaPlayer的MP){
                            // TODO自动生成方法存根
                            mp.release();
                        }

                    });
                    mp.start();
                }

            });
 

I am trying to play a sound file on the click of a button. The sound is just 1 sec long. It plays well the first few times I click the button, but after a while it gives a NullPointerException. Here's the code:

button[i].setOnClickListener(new OnClickListener() {
    public void onClick(View view) {        
        mp = MediaPlayer.create(Test.this, R.raw.mysound);   
        mp.start();
    }
});

And here's the exception:

07-29 23:07:27.690: ERROR/AndroidRuntime(10542): Uncaught handler: thread main exiting due to uncaught exception
07-29 23:07:27.710: ERROR/AndroidRuntime(10542): java.lang.NullPointerException
07-29 23:07:27.710: ERROR/AndroidRuntime(10542):     at com.example.mypackage.Test$3.onClick(Test.java:270)

解决方案

Thanks you for your answers! Appreciate it!

Here's how I finally managed to get it work:

            button[i].setOnClickListener(new OnClickListener() {
                public void onClick(View view) {

                    mp = MediaPlayer.create(Test.this, R.raw.mysound);
                    mp.setOnCompletionListener(new OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            // TODO Auto-generated method stub
                            mp.release();
                        }

                    });   
                    mp.start();
                }

            });

这篇关于Android的 - 播放声音的按钮,点击 - 空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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