54

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.

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.

0

2 Answers 2

193

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

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

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

7
  • @QuinDa Great! Don't forget to click the checkmark next to an answer if it worked for you--it'll help you get better answers from us in the future! ;)
    – Cat
    Commented Nov 12, 2012 at 21:03
  • I tried it but it says: Vote Up requires 15 reputation ):
    – QuinDa
    Commented Nov 13, 2012 at 10:16
  • @QuinDa The checkmark, not the up arrow (which, yes, needs 15 reputation). But it seems you found it already! :)
    – Cat
    Commented Nov 13, 2012 at 16:31
  • Storm the up vote! Commented Jul 13, 2016 at 22:07
  • 1
    I fixed it with the following code: drawable = resources.getDrawable(resources.obtainTypedArray(R.array.array_name).getResourceId(array_index, 0), context.getTheme());
    – Dmitry
    Commented Aug 31, 2018 at 6:14
4

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.

4
  • 5
    I think Resources.getIdentifier is probably an easier method than this.
    – Tim
    Commented Nov 12, 2012 at 20:45
  • Yes but this solution is faster (by more than 40%)
    – An-droid
    Commented Mar 19, 2014 at 15:51
  • @An-droid - could you provide some source for this? i checked it and found the difference to be negligible. i also read that blogpost everyone keeps mentioning, but there are no metrics beside a dubious claim that reflection is 5 times faster. To me it seems that the results only depend on where the resource is located in the R file (the more to the top, the faster the lookup).
    – katzenhut
    Commented Jul 29, 2015 at 12:23
  • 1
    @An-droid - i found the link to the post in case you would like to check: daniel-codes.blogspot.de/2009/12/…
    – katzenhut
    Commented Jul 29, 2015 at 12:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.