I need get a resource ID
from string
String s = "R.raw.button5";
final MediaPlayer mp2 = MediaPlayer.create(this,Integer.valueOf((s));
I need get a resource ID
from string
String s = "R.raw.button5";
final MediaPlayer mp2 = MediaPlayer.create(this,Integer.valueOf((s));
You can use getIdentifier(....). If you have button with id "R.id.button5" then this is your code.
int id = getResources().getIdentifier("button5", "id", context.getPackageName());
final MediaPlayer mp2 = MediaPlayer.create(this,id);
You can get the resource id from resource name with getIdentifier():
getIdentifier
int getIdentifier (String name,
String defType,
String defPackage)Return a resource identifier for the given resource name. A fully qualified resource name is of the form "package:type/entry". The first two components (package and type) are optional if defType and defPackage, respectively, are specified here.
Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
To get the resource raw id, you can use something like:
Context context = getContext(); // base context or application context
int resId = getResources().getIdentifier("button5", "raw",
context.getPackageName());
// Or
int resId = getResources().getIdentifier("raw/button5", null,
context.getPackageName());
But you need to remember, as the note in documentation says, you better using the pregenerated resource id instead of getting from the resource name. It's because getIdentifier()
need time to found the matching resource name as in the following code (from Resources):
public int getIdentifier(String name, String defType, String defPackage) {
if (name == null) {
throw new NullPointerException("name is null");
}
try {
return Integer.parseInt(name);
} catch (Exception e) {
// Ignore
}
return mAssets.getResourceIdentifier(name, defType, defPackage);
}
The other reason is, hard coding a resource name with R.raw.button5
is a maintenance nightmare. Because there's a probability that you will change the name in the future, then you end up with a resource name pointing to nowhere.