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 pa开发者_运维知识库ssing 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.
I would suggest you using my method to get a resource ID. If you make simple exception handling there, you will see, that if your resource does not exist it will be thrown. That would gracefully resolve your issue.
Here's the code:
/**
* @author Lonkly
* @param variableName - name of drawable, e.g R.drawable.<b>image</b>
* @param с - class of resource, e.g R.drawable, of R.raw
* @return integer id of resource
*/
public static int getResId(String variableName, Class<?> с) {
Field field = null;
int resId = 0;
try {
field = с.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
精彩评论