How to gracefully check if a raw resource exists?

I have a method in my class called play, and I want to play, which plays an audio file. Which file is played depends on the value of the current audio index. In principle, there is such a switch:

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 switching, I want to check if rId is valid before passing it to MediaPlayer.create (this, rId). It seems that create does not throw an exception if the identifier does not exist or cannot be opened. So what should I check before passing it on?

How to gracefully handle this? So far, I just assumed that rId will always be correct, but I would like to check to make sure.

+6
source share
2 answers

You can get the resource identifier from the file name of this method . It will return 0 if it is not a valid resource identifier. See this question for more details.

The project should not compile if the resource does not exist, since R.resourcetype.resourcename will not exist in R.java. This is useful if you do not know what resources you have at runtime.

+4
source

I would suggest you use my method to get the resource identifier. If you do simple exception handling, you will see that if your resource does not exist, it will be thrown. This will elegantly solve your problem.

Here is the code:

 /** * @author Lonkly * @param variableName - name of drawable, eg R.drawable.<b>image</b> * @param  - class of resource, eg 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; } 
0
source

Source: https://habr.com/ru/post/893742/


All Articles