dotaneli dotaneli - 3 months ago 25
Android Question

Android loading images to ImageView from drawable using only the file name

I need to load an image from drawable to an image view.
The ImageView is part of a ListViewItem, hence I have a large number of items and a large number of images.

When loading, the app parses a JSON file which states, among other information, the file name to be loaded per list item.

for example, "test_a.jpg".

The file "test_a.jpg" is located in "drawable".

I want, on runtime, to load drawable/test_a.jpg, test_b.jpg, big_chief.jpg and so on...

int intCurrImageResourceID = this.context.getResources().getIdentifier(strPictureName, "drawable", context.getPackageName());


any ideas on how to achieve that?

*** EDIT ****
It turns out that you shouldn't use file extension. So image.jpg is wrong. image is right. Thanks all. Especially @Augusto Carmo.

Answer

---- updated (correct answer)

A question, in your code, is strPictureName equals, for example, to something like this: "myDogPicture.png"? If yes, you should remove ".png" from the string first. Test it :) To get images from drawable with resource ids, you should not use the image extension.

---- old answer

You can achieve this with the following code:

// example - your ImageView
ImageView myImageView = (ImageView)findViewById(R.id.my_image_view);
// suppose the name of your image in drawable/ is my_image_name.jpg.
myImageView.setImageResource(R.drawable.my_image_name);

If you already know what the mapping between strings and resource ids will be, what do you think about using enum? example:

public enum MyImage{
        CAT_IMAGE("cat.png", R.drawable.cat),
        DOG_IMAGE("dog.png", R.drawable.dog),
        HORSE_IMAGE("horse.png", R.drawable.horse);

        private final String fileName;
        private final int resId;

        MyImage(String fileName, int resId){
            this.fileName = fileName;
            this.resId = resId;
        }

        /**
         * 
         * @param imageFileName
         * @return -1 if image not found
         */
        public int getResId(String imageFileName){
            int resId = -1;
            for (MyImage myImage : MyImage.values()) {
                if (imageFileName.equals(myImage.fileName)){
                    resId = myImage.resId;
                    break;
                }
            }
            return resId;
        }
    }
Comments