19

Currently I'm drawing a PNG image in my Android application like so:

ImageView image = new ImageView(context);
image.setImageDrawable(context.getResources().getDrawable(R.drawable.testimage))

If I have a list of image names in a database, is there a way to set the drawable above using the image name? I already have the code to go through the database, I'm just looking to draw the image based on the value taken from here.

For example, a record for the DB:

ID:    Name:    ImageName:
-      Test     testimage

So when I'm reading this record, I have a string with the value of "testimage" and I'd then want to set the image drawable to R.drawable.testimage.

One way I was thinking of doing it would be something like this:

int image = R.drawable.blank; // blank image

// testimage.png is the image name from the database
if(imageName.toString().equals("testimage.png"))
    image = R.drawable.testimage;
else if(imageName.toString().equals("another.png"))
    image = R.drawable.another;
else if(imageName.toString().equals("etc.png"))
    image = R.drawable.etc;

However this isn't very efficient!

Thanks

ingh.am
  • 25,981
  • 43
  • 130
  • 177

4 Answers4

26

There is a method for doing that, you can retreive resource IDs by string using Resources.getIdentifier() http://developer.android.com/reference/android/content/res/Resources.html

Something like:

int resourceId = Activity.getResources().getIdentifier("testimage", "drawable", "your.package.name");
GeekYouUp
  • 1,651
  • 11
  • 10
23

I'm using:

int resId = getResources().getIdentifier("testimage", "drawable", getPackageName());
image.setImageResource(resId);

"testimage" - corresponds to for instance testimage.jpg, i.e. dont include ".jpg"

"drawable" - is the resource type, like in: @drawable/testimage

Check Resources.getIdentifier(...)

Erik S
  • 502
  • 3
  • 11
0

Put you images in the assets/ folder and open

image.setImageURI("file:///android_asset/" + nameFromDB);
Mikpa
  • 1,912
  • 15
  • 20
-2

String path = "sdcard/camera_app/name.jpg"; img.setImageDrawable(Drawable.createFromPath(path));

Mudasar
  • 159
  • 1
  • 7
  • Without any explanation, this is not helpful. – J Fabian Meier Aug 02 '16 at 18:46
  • You can use path for different images example String path = "sdcard/camera_app/image1.jpg"; or String path = "sdcard/camera_app/image2.jpg" this can be use in if else condtion to draw a image only you want. – Mudasar Aug 03 '16 at 17:14