3

I need get a resource ID from string

String s = "R.raw.button5";

final MediaPlayer mp2 = MediaPlayer.create(this,Integer.valueOf((s));
Cœur
  • 37,241
  • 25
  • 195
  • 267
Maatoug Omar
  • 173
  • 1
  • 7
  • 4
    Welcome to SO. **We are here to help in your code**, if you haven't tried anything then we cant help much. Please take a [tour](https://stackoverflow.com/tour) of SO and read the [help page](https://stackoverflow.com/help) to see how to ask a question. – Syfer Aug 20 '17 at 23:54

2 Answers2

3

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);
zihadrizkyef
  • 1,849
  • 3
  • 23
  • 46
1

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.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96