Find drawable by string

Possible Duplicate:
Android – Open resource from @drawable String

First of all sorry for the title but I don’t know exactly what title I can set.

  • Alarm Manager - Scheduling multiple Non-repeating events
  • Out of memory error on android emulator, but not on device
  • How to handle the Ripple effect on 9-patch and CardView, and have control over the states of the selector?
  • Android, how to set imageview with percentage in relativelayout
  • What's the convention for java package names without a domain association?
  • Any good ORM tools for Android development?
  • Ok, here’s my question:

    I will recibe from a external database a string for example: ‘picture0001’.

    In the folder res/drawable I have a picture which name is picture0001.

    I would like to set that picture as background (source) of a ImageView.

    The question is, how can I look for this picture with the string I got from the external database.

    Thank you so much.

  • uses-sdk element cannot have a “tools:node” attribute
  • Android Test Project Directory Structure When Using Eclipse
  • How to write custom ExpandableListAdapter
  • Padding between ActionBar's home icon and title
  • How to install/replace on Android without using Eclipse
  • Couchdb on Android
  • 2 Solutions collect form web for “Find drawable by string”

    Yes, you can look it up by name using Resources.getIdentifier().

    Context context = imageView.getContext();
    int id = context.getResources().getIdentifier("picture0001", "drawable", context.getPackageName());

    It’s not efficient, but it works to look up occasional resources.

    You can also use reflection like this:

    Class c = Class.forName("your.project.package.R");
    Field f = c.getDeclaredField("drawable");
    Class d = f.getDeclaringClass();
    Field f2 = d.getDeclaredField("yourstring");
    int resId = f2.getInt(null);
    Drawable d = getResources().getDrawable(resId);

    Though, the best solution is what MarvinLabs suggested.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.