18

I want to use a variable instead of R.drawable.myimage because I have a database with the image's names. I get the name from the database and I want to use the drawable resource with this name.

String flagimage = "R.drawable." + myHelper.getFlagImage(5);
int resourceId = Integer.parseInt(flagimage);
Bitmap flag = BitmapFactory.decodeResource(getResources(), resourceId);
Alex
  • 847
  • 3
  • 15
  • 23

2 Answers2

40

You can use the name of a resource like

getIdentifier (String name, String defType, String defPackage);

getResources().getIdentifier("us","drawable","com.app");

The above function will return an integer value same as R.drawable.us.

This is how you access with resource names.

Nikunj Paradva
  • 15,332
  • 5
  • 54
  • 65
blessanm86
  • 31,439
  • 14
  • 68
  • 79
  • 2
    Just a quick note [getIdentifier](http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29) returns `0` if no such resource was found. (0 is not a valid resource ID.) – razz Feb 07 '16 at 05:44
18

You can use this code to get the identifier...

 Resources res = this.getResources(); 
 int resID = res.getIdentifier(imagename, "drawable", this.getPackageName());
mAndroid
  • 5,087
  • 6
  • 25
  • 33