200

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,160
  • 4
  • 16
  • 31
Aswan
  • 4,947
  • 10
  • 44
  • 67
  • 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

366

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,139
  • 15
  • 21
Maragues
  • 36,772
  • 14
  • 93
  • 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
  • 2
    @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
158

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
  • 10,654
  • 5
  • 58
  • 68
Rabid
  • 2,942
  • 2
  • 23
  • 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
26
int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
DaveShaw
  • 50,828
  • 16
  • 110
  • 139
user1393422
  • 269
  • 3
  • 2
23

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
  • 11,316
  • 11
  • 73
  • 98
aminography
  • 20,387
  • 13
  • 62
  • 71
15

A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.

int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);
OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
Muhammad Adil
  • 437
  • 6
  • 11
11
// 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,544
  • 15
  • 23
7

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
  • 151,199
  • 17
  • 111
  • 216
Vivienne Fosh
  • 1,673
  • 17
  • 24
  • 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
  • 3
    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".

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,115
  • 3
  • 35
  • 41
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
  • 986
  • 8
  • 25