210

I want to access a resource like a String or a Drawable by its name and not its int id.

Which method would I use for this?

Kuya
  • 7,280
  • 4
  • 19
  • 31
Aswan
  • 5,085
  • 10
  • 46
  • 70
  • 2
    possible duplicate of [How can i get the resource id of an image if I know its name?](http://stackoverflow.com/questions/3042961/how-can-i-get-the-resource-id-of-an-image-if-i-know-its-name) – ghoti Dec 07 '12 at 18:55

10 Answers10

377

If I understood right, this is what you want

int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());

Where "this" is an Activity, written just to clarify.

In case you want a String in strings.xml or an identifier of a UI element, substitute "drawable"

int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());

I warn you, this way of obtaining identifiers is really slow, use only where needed.

Link to official documentation: Resources.getIdentifier(String name, String defType, String defPackage)

Artyom
  • 1,165
  • 14
  • 22
Maragues
  • 37,861
  • 14
  • 95
  • 96
  • 3
    This is pretty useful in the context of writing tests to make sure certain strings exist or etc. – Ehtesh Choudhury May 01 '15 at 22:14
  • 1
    I don't know man, I've added a Log before and after getIdentifier() with timestamp and it showed me that it gets executed in 0 - 1 ms! So it's not slow, it's super fast! I'm using it to get images from resources and it works perfectly. Tested on Nexus5x. – Kirill Karmazin Apr 25 '17 at 21:16
  • 3
    @KirillKarmazin: Nexus5X is a decently fast phone, and 1ms for such a call is quite slow. Remember that each UI frame is only 16ms. – Mooing Duck Aug 15 '18 at 21:22
  • hello, if i want to get id from raw folder, so i need to use "int resourceId = this.getResources().getIdentifier("nameOfResource", "raw", this.getPackageName());??? plz help – famfamfam Aug 23 '20 at 13:24
161

It will be something like:

R.drawable.resourcename

Make sure you don't have the Android.R namespace imported as it can confuse Eclipse (if that's what you're using).

If that doesn't work, you can always use a context's getResources method ...

Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);

Where this.context is intialised as an Activity, Service or any other Context subclass.

Update:

If it's the name you want, the Resources class (returned by getResources()) has a getResourceName(int) method, and a getResourceTypeName(int)?

Update 2:

The Resources class has this method:

public int getIdentifier (String name, String defType, String defPackage) 

Which returns the integer of the specified resource name, type & package.

Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
Rabid
  • 2,984
  • 2
  • 25
  • 25
  • Thankq for your reply .R.drawable.resourcename i am using now i need to get its integer value by passing resourcename – Aswan Aug 13 '10 at 11:45
  • 2
    `R.drawable.resourcename` *is* the integer. – Rabid Aug 13 '10 at 11:46
  • Hi Rabid.what you said that's is there any way by accessing R.drawable .resource value by passing resouce – Aswan Aug 13 '10 at 11:47
  • i need that integer value by passing resourcename dynamically – Aswan Aug 13 '10 at 11:48
  • Thankq like this i want and i want to get drawable resource id.how i wil to it – Aswan Aug 13 '10 at 11:57
  • As maragues has suggested, it would be like `this.context.getResources().getIdentifier("package:type/entry", null, null);` where `"package:type/entry"` would be for example, `"com.your.package:drawable/resourcename"` ? – Rabid Aug 13 '10 at 12:05
  • i used context.getResources().getIdentifier() method , it worked like a spiderman :) – John Jan 14 '16 at 12:00
28

Kotlin Version via Extension Function

To find a resource id by its name In Kotlin, add below snippet in a kotlin file:

ExtensionFunctions.kt

import android.content.Context
import android.content.res.Resources

fun Context.resIdByName(resIdName: String?, resType: String): Int {
    resIdName?.let {
        return resources.getIdentifier(it, resType, packageName)
    }
    throw Resources.NotFoundException()
}

Usage

Now all resource ids are accessible wherever you have a context reference using resIdByName method:

val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.    
Mahozad
  • 18,032
  • 13
  • 118
  • 133
aminography
  • 21,986
  • 13
  • 70
  • 74
27
int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
user1393422
  • 279
  • 3
  • 2
12
// image from res/drawable
    int resID = getResources().getIdentifier("my_image", 
            "drawable", getPackageName());
// view
    int resID = getResources().getIdentifier("my_resource", 
            "id", getPackageName());

// string
    int resID = getResources().getIdentifier("my_string", 
            "string", getPackageName());
Manthan Patel
  • 1,784
  • 19
  • 23
6

I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.

Here's the code:

/**
 * @author Lonkly
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param с - class of resource, e.g R.drawable.class or R.raw.class
 * @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;

}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Vivienne Fosh
  • 1,751
  • 17
  • 24
  • 1
    It will not work for all cases. For example if you have content than the R.string class will have a string_name field. And your method will not work in this point. – ddmytrenko Oct 22 '13 at 14:32
  • 4
    Also your method is not fast actually. Because Java class serialization is never working quick. – ddmytrenko Oct 23 '13 at 10:39
3

In Kotlin following works fine for me:

val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())

If resource is place in mipmap folder, you can use parameter "mipmap" instead of "drawable".

2

If you need to do this in compose, here how you can do it:

val context = LocalContext.current
val drawableId = remember(iconName) {
     //this block will re-calculate each time iconName has changed
     val resId by derivedStateOf {
        context.resources.getIdentifier(
             iconName,
             "drawable",
             context.packageName
            )
        }
    if (resId != 0) resId else R.drawable.some_fallback_icon //it doesn't throw an error instead resId becomes 0, so we need to check if 0 aka couldn't find the drawable.
   }

//then use drawableId

like painterResource(id = drawableId)

Eren Utku
  • 1,731
  • 1
  • 18
  • 27
1

in addition to @lonkly solution

  1. see reflections and field accessibility
  2. unnecessary variables

method:

/**
 * lookup a resource id by field name in static R.class 
 * 
 * @author - ceph3us
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param с            - class of resource, e.g R.drawable.class or R.raw.class
 * @return integer id of resource
 */
public static int getResId(String variableName, Class<?> с)
                     throws android.content.res.Resources.NotFoundException {
    try {
        // lookup field in class 
        java.lang.reflect.Field field = с.getField(variableName);
        // always set access when using reflections  
        // preventing IllegalAccessException   
        field.setAccessible(true);
        // we can use here also Field.get() and do a cast 
        // receiver reference is null as it's static field 
        return field.getInt(null);
    } catch (Exception e) {
        // rethrow as not found ex
        throw new Resources.NotFoundException(e.getMessage());
    }
}
ceph3us
  • 7,326
  • 3
  • 36
  • 43
0

I have found this class very helpful to handle with resources. It has some defined methods to deal with dimens, colors, drawables and strings, like this one:

public static String getString(Context context, String stringId) {
    int sid = getStringId(context, stringId);
    if (sid > 0) {
        return context.getResources().getString(sid);
    } else {
        return "";
    }
}
Diego Malone
  • 1,044
  • 9
  • 25