I have a method in my class called play and I want play which plays an audio file. Which file is played depends on the classes current audioIndex value. Basically, there’s a switch like this:
int rId;
switch (audioIndex){
case 0: rId = R.raw.e0.wav; break;
case 1: rId = R.raw.e1.wav; break;
default: rId = R.raw.error.wav; break;
}
After the switch I want to verify if the rId is valid before I pass it to MediaPlayer.create(this, rId). It appears create does not throw an exception if the id doesn’t exist or can’t be opened. So I must check before passing it?
How to gracefully handle this? Until now I have just assumed the rId will always be correct but I would like to check to make sure.
You can get the resource identifier from the filename with this method. It will return 0 if it is not a valid resource ID. See this question for more.
The project shouldn’t compile if the resource doesn’t exist though, as R.resourcetype.resourcename won’t exist in R.java. This is only useful if you don’t know what resources you’ll have at runtime.