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.

  • Xamarin Android EditText enter key
  • Can onMeasure be skipped when adding a View to a ViewGroup?
  • Observing changes in android content observer for Audio.Media.EXTERNAL_CONTENT_URI
  • TabLayout tab style
  • How to handle multiple fragment interaction listeners in one Activity properly?
  • What is difference between DVM and ART ? Why DVM has been officially replaced with ART in Lollipop?
  • 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.

    Related posts:

    Android: can't replace one fragment with another
    How to remove listview all items
    Building an Android Project from Command Line with Eclipse
    Android Studio - Creating Modules without copying files?
    What's a good library for parsing mathematical expressions in java?
    GoogleApiClient.connect()' was expected to be of type interface but was found to be virtual
  • Cannot detect when outgoing call is answered in Android
  • Change layout_scrollFlags programmatically in CollapsingToolbarLayout
  • How to use retrofit as a singleton while using gson convertor?
  • How do I determine if Android can handle PDF
  • onListItemClick is not working for listview?
  • Variable package name with Maven Android Plugin
  • 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.