Reputation: 9225
I have the following function:
strNameValue = prefs.getString("NamePosition", "");
inNameValueConversion = Integer.parseInt(strNameValue);
if (inNameValueConversion == 0) {
DisplayInformation(inNameValueConversion, R.raw.audio01);
}
if (inNameValueConversion == 1) {
DisplayInformation(inNameValueConversion, R.raw.audio02);
}
if (inNameValueConversion == 2) {
DisplayInformation(inNameValueConversion, R.raw.audio03);
}
if (inNameValueConversion == 3) {
DisplayInformation(inNameValueConversion, R.raw.audio04);
}
Because all the audio file starts with audio
and only the number changes at the end I wanted to create a function which allows me to use less code like this:
public void DisplayInformation(int inNum, final int inSoundResource) {
if (inSoundResource < 2) {
strIConv = String.valueOf("0" + inSoundResource);
inConv = Integer.parseInt(strIConv);
int k = R.raw.audio+"inConv";
}
}
I get the following error: audio cannot be resolved or is not a field
How do I edit the above code so I can just use one function instead of using so many IF statement, since it will be 90+ times.
Upvotes: 1
Views: 891
Reputation: 8598
You can use getIdentifier(), so your code would look like this:
public void displayInformation(int inNum) {
String id = "audio";
// for inNum < 9, we need to add 0, so for example when you pass 0
// id will be 01, not 1
if (inNum < 9) then id += "0";
//based on your code, 0 - audio01, 1 - audio02 etc, so add 1
id += (inNum + 1);
// call getIdentifier with string containing resource name, which are in your raw folder
// and in your package
int k = getResources().getIdentifier(id, "raw", "your.package.name.here");
//k now contains an id of your resource, so do whatever you want with it
}
and your code can then be reduced to this:
strNameValue = prefs.getString("NamePosition", "");
inNameValueConversion = Integer.parseInt(strNameValue);
displayInformation(inNameValueConversion);
Remember to use your package name in the call to getIdentifier().
Docs are here: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier(java.lang.String, java.lang.String, java.lang.String)
Upvotes: 3
Reputation: 8870
Building R values that way won't work -- you'll need to use reflection instead.
For example:
import java.lang.reflect.Field;
/* ... */
int id = R.id.class.getField("video" + i).getInt(0);
Upvotes: 1
Reputation: 268
You could try to do it like it is mentioned in this post: https://stackoverflow.com/a/5626631/3178834
In your case, you have to create an array for all audio files as resources xml and then load it with res.getXml
into java. Just follow the link from above.
Upvotes: 1