How do I get the resource id of an image if I know its name?

105,097

Solution 1

With something like this:

String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

Solution 2

You can also try this:

try {
    Class res = R.drawable.class;
    Field field = res.getField("drawableName");
    int drawableId = field.getInt(null);
}
catch (Exception e) {
    Log.e("MyTag", "Failure to get drawable id.", e);
}

I have copied this source codes from below URL. Based on tests done in this page, it is 5 times faster than getIdentifier(). I also found it more handy and easy to use. Hope it helps you as well.

Link: Dynamically Retrieving Resources in Android

Solution 3

Example for a public system resource:

// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");

alert

Another way is to refer the documentation for android.R.drawable class.

Solution 4

You can use this function to get a Resource ID:

public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException {
    try {
        return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
    } catch (Exception e) {
        throw new RuntimeException("Error getting Resource ID.", e)
    } 
}


So if you want to get a Drawable Resource ID, you can call the method like this:

getResourseId(MyActivity.this, "myIcon", "drawable", getPackageName());

(or from a fragment):

getResourseId(getActivity(), "myIcon", "drawable", getActivity().getPackageName());


For a String Resource ID you can call it like this:

getResourseId(getActivity(), "myAppName", "string", getActivity().getPackageName());

etc...


Careful: It throws a RuntimeException if it fails to find the Resource ID. Be sure to recover properly in production.

Read this

Share:
105,097
Admin
Author by

Admin

Updated on July 21, 2022

Comments

  • Admin
    Admin almost 2 years

    How do I get the resource id of an image if I know its name (in Android)?

  • Select0r
    Select0r almost 14 years
    Thanks, that helped me find a solution to a simliar problem! I'll use getResources().getIdentifier(name, "id", getPackageName()); to get the ID of an ImageButton (as you would with R.id.name).
  • larham1
    larham1 almost 13 years
    Note that the drawable name should NOT include an extension like ".png"
  • Pedro Rainho
    Pedro Rainho about 12 years
    this might be faster but I found it can get you in trouble if you use proguard. This doesn't worked in proguard at least for me
  • John Watson
    John Watson almost 12 years
    what exactly goes in the variable name ? I want to find the id of a button whose reference i know, in my case it is button1
  • Bahadır Yıldırım
    Bahadır Yıldırım over 10 years
    Catching generic exceptions is an especially bad idea. Furthermore, note that if there are no hard references to the drawable, Proguard may optimize the reference away as it doesn't believe that it's being used anywhere.
  • VSB
    VSB over 10 years
    I understand now :) you mean that during optimization drawableName changes and resource cannot be found using this method, if i am right? :)
  • Richard Le Mesurier
    Richard Le Mesurier about 10 years
    I think you need to remove static from that, otherwise getResources() will not work.
  • ToolmakerSteve
    ToolmakerSteve about 9 years
    @VSB: if your last comment is a response to Paul Lammertsma comment immediately above: No, he means that Proguard doesn't know this is a reference to the resource, and so might remove the resource, believing that it is not used.
  • Srujan Barai
    Srujan Barai almost 9 years
    getResource() and getPackageName() showing error. cannot resolve method
  • naXa stands with Ukraine
    naXa stands with Ukraine over 8 years
    @Milaaaad what do you mean?
  • Milaaaad
    Milaaaad over 8 years
    it means i confused by resources in the code and i use it in non activity class
  • The Berga
    The Berga about 8 years
    @Srujan Barai, getResource() and getPackageName() are methods from Activity.
  • Someone Somewhere
    Someone Somewhere almost 8 years
    once you use xxxxhdpi, xxhdpi, etc. this method becomes less useful
  • VSB
    VSB almost 8 years
    @SomeoneSomewhere You mean it is deprecated?
  • Someone Somewhere
    Someone Somewhere almost 8 years
    I'm sorry - ignore my comment... it was my fault, this approach works well with various image sizes (xxxhdpi, etc)
  • naXa stands with Ukraine
    naXa stands with Ukraine almost 8 years
    @Milaaaad This method is for system resources. They don't depend on context.
  • Veer
    Veer over 7 years
    @Richard Le Mesurier, can you explain why? Thank you.
  • Richard Le Mesurier
    Richard Le Mesurier over 7 years
    @Leo.Han At the time I made that comment, the Context was not available. Fix was either to remove static and move it into a Context (e.g. Activity or Application); or alternate fix is what Jonathan did in his edit, which is to pass in a Context to the method.
  • Veer
    Veer over 7 years
    @Richard Le Mesurier, I checked the edit history just now, it's just as what you said, thank you for your kindly reply after so many years :)
  • CatCap
    CatCap over 6 years
    mDrawableName should be in lower register! Otherwise reID will be 0
  • Prince
    Prince over 3 years
    Just make sure Resource Id is not 0 else it will throw Exception. The resource with this name must be present in the drawable folder.