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.