Java – Is it possible to get mipmap images by id?

Is it possible to get mipmap images by id?… here is a solution to the problem.

Is it possible to get mipmap images by id?

I’ve stored image icons in the res/mipmap folder of my android project. Each of them has their own image ID. I want to check if I have an image by image ID. I want to do something similar

String input_id = "blue_image";
ImageView image;
if (image.getImageByID(input_id)){  ## if image with blue_image exists
    image.setImageResource(...);
}

If I knew blue_image existed, then I usually get it

image.setImageResource(R.mipmap.blue_image);

There seem to be two questions in this question. One is to check if the image exists by ID, and the second is to find something similar to the getattr() python function in java.

If you have any other solutions for similar situations, you are also welcome to provide them.

Solution

Try this in your Activity class:

int imageId = getResources().getIdentifier(inputId, "drawable", getPackageName());

if (imageId > 0) {
    image.setImageResource(imageId);
}

The point is that if no resource is found, getIdentifier() returns 0.

Related Problems and Solutions