0

I'm trying to play .ogg files I have placed in the raw folder by click listener on an imageview. This method is inside the onCreate of an Activity that extends AppCompatactivity.

Can anyone help me identify what causes the app to crash when I click on the ImageView? And how to do it properly?

ImageView soundButton = (ImageView) this.findViewById(R.id.soundbtn);
soundButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String s = "a"+num+".ogg";
        Log.i("mytag", "inside" + s);
        Resources res = getApplicationContext().getResources();
        int soundID = res.getIdentifier(s, "raw", getApplicationContext().getPackageName());
        MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), soundID);
        mediaPlayer.start(); // no need to call prepare(); create() does that for you
    }
});

Edit:

It is working if I try the normal method:

MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationcontext(), R.raw.a1);
mediaPlayer.start(); // no need to call prepare(); create() does that for you

But I want to play different file based on the num variable.

I used this Android get R.raw from variable for reference.

Xgh05t
  • 210
  • 2
  • 10
  • We would need to see the complete [stack trace from the crash](https://stackoverflow.com/a/23353174) to be certain, but I would guess that the immediate issue is that `getIdentifier()` is returning `0`. You don't include the file extension in the name passed to that method. That is, remove `+".ogg"` from `String s`. – Mike M. Apr 06 '20 at 01:48
  • That did fix it, but it's strange because initially I did not have that `.ogg` part and I only added it while trying to fix it. – Xgh05t Apr 06 '20 at 01:50
  • Perhaps there was some other minor error while you were changing things around for testing? Anyhoo, glad you got it working. Cheers! – Mike M. Apr 06 '20 at 01:51

0 Answers0