Android - play sound on button click - Null pointer exception Android - play sound on button click - Null pointer exception android android

Android - play sound on button click - Null pointer exception


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


You can also try:

final soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);final sound = soundPool.load(this, R.raw.mysound, 1);button[i].setOnClickListener(new OnClickListener(){     public void onClick(View view)     {                soundPool.play(sound, 1.0f, 1.0f, 0, 0, 1.0f);     }});


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