[TinyTut] - Get ResourceName by its ID
What you learn: You will learn how get Name of a Resource if you only know the ID. This Tutorial uses the Java Reflection API (no need for you to code on your own
).Difficulty: 1.5 of 5

Description: I was not aware of a function returning the name of a Resource (what is the filename without the file-ending) of a known resource (knowing only its ID), so I coded one myself...
Example-Call:
Using java Syntax Highlighting
- // Example-Call:
- String resName = getResourceNameFromClassByID(R.drawable.class, R.drawable.icon);
- // resName would be 'icon'.
Parsed in 0.031 seconds, using GeSHi 1.0.8.4
The Source:
Using the Java Reflection API this was not hard to do.
Using java Syntax Highlighting
- /**
- * Determines the Name of a Resource,
- * by passing the <code>R.xyz.class</code> and
- * the <code>resourceID</code> of the class to it.
- * @param aClass : like <code>R.drawable.class</code>
- * @param resourceID : like <code>R.drawable.icon</code>
- * @throws IllegalArgumentException if field is not found.
- * @throws NullPointerException if <code>aClass</code>-Parameter is null.
- * <br><br>
- * <b>Example-Call:</b><br>
- * <code>String resName = getResourceNameFromClassByID(R.drawable.class, R.drawable.icon);</code><br>
- * Then <code>resName</code> would be '<b>icon</b>'.*/
- public String getResourceNameFromClassByID(Class<?> aClass, int resourceID)
- throws IllegalArgumentException{
- /* Get all Fields from the class passed. */
- Field[] drawableFields = aClass.getFields();
- /* Loop through all Fields. */
- for(Field f : drawableFields){
- try {
- /* All fields within the subclasses of R
- * are Integers, so we need no type-check here. */
- /* Compare to the resourceID we are searching. */
- if (resourceID == f.getInt(null))
- return f.getName(); // Return the name.
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /* Throw Exception if nothing was found*/
- throw new IllegalArgumentException();
- }
Parsed in 0.033 seconds, using GeSHi 1.0.8.4
Let us know if it helped you

Regards,
plusminus




