How to get a resource id with a known resource name?

JavaAndroidAndroid Resources

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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)

Solution 2 - Java

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.

Solution 3 - Java

int resourceID = 
    this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());

Solution 4 - Java

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")
.
.
.    

Solution 5 - Java

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);

Solution 6 - Java

// 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());

Solution 7 - Java

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;

}

Solution 8 - Java

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".

Solution 9 - Java

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 "";
	}
}

Solution 10 - Java

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());
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAswanView Question on Stackoverflow
Solution 1 - JavaMaraguesView Answer on Stackoverflow
Solution 2 - JavaRabidView Answer on Stackoverflow
Solution 3 - Javauser1393422View Answer on Stackoverflow
Solution 4 - JavaaminographyView Answer on Stackoverflow
Solution 5 - JavaMuhammad AdilView Answer on Stackoverflow
Solution 6 - JavaManthan PatelView Answer on Stackoverflow
Solution 7 - JavaVivienne FoshView Answer on Stackoverflow
Solution 8 - JavaJens van de MötterView Answer on Stackoverflow
Solution 9 - JavaDiego MaloneView Answer on Stackoverflow
Solution 10 - Javaceph3usView Answer on Stackoverflow