Play Sound on Button Click in Android giving Null Pointer Exception

Viewed 103

I am trying to play a sound on button click but it is giving a null pointer exception. I looked at some answers on StackOverflow but nothing helped

package com.example.testproject;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = findViewById(R.id.button);
        final MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.dice_sound);
        btn.setOnClickListener(v -> {
            mp.start();
            mp.release();
        });
    }
}

Error: As per the error showing in Logcat the variable mp is considered as null. I can't find out the fix for it.

2 Answers

The error is occurring because the sound .wav is not supported by the device that I am running on the test app. It is running on a different device that supports .wav file format. I have converted the file type to mp3 and now it is working on both devices.

Thanks to everyone for your reply...

Try this in your click listener

mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(true);
try {
      mediaPlayer.setDataSource(this, R.raw.dice_sound);
      mediaPlayer.prepare();
      mediaPlayer.setOnPreparedListener(this);
      mediaPlayer.start(); // if app craches on this line commit it then check 
    } catch (Exception e) {
         e.printStackTrace();
    }

Make sure that you should stop the mediaplayer before exist from the activity. You can do this in the click of the stop button. if you dont want to add the stop button then in the activity life cycle you should override onDestory and stop the player in the onDestory function.

Related