views:

309

answers:

2

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 Chris

A: 

It might solve your problem,

button[i].setOnClickListener(new OnClickListener() {
        public void onClick(View view) {     
                new Thread(){
                public void run(){
                              mp = MediaPlayer.create(Test.this, R.raw.mysound);   
                               mp.start();
                }
               }.start();
               }
           });
sohilv
Still works fine for the first few clicks, and then gives a null pointer exception, particularly when I click buttons quickly in succession.
Chris
can you try,1) putting check before starting. i mean check if player is in playing stage then don't execute this statementmp = MediaPlayer.create(Test.this, R.raw.mysound); mp.start();or2) make mp as local variable
sohilv
A: 

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.start();
                    mp.setOnCompletionListener(new OnCompletionListener() {

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

                    });
                }

            });
Chris