Android ImageView setImageResource in code-ThrowExceptions

Exception or error:

I have an imageView that i want to display a little icon of the country that you are currently in. I can get the country code, but problem is i can’t dynamically change the imageView resource. My image files are all lowercase (Example: country code=US, image file=us)

My code (countryCode is the current countryCode in uppercase letters):

    String lowerCountryCode = countryCode.toLowerCase();
    String resource = "R.drawable." + lowerCountryCode;

Now, of course this will not work because setImageResource wants an int, so how can i do this?
Thanks in advance 😀

How to solve:

One easy way to map that country name that you have to an int to be used in the setImageResource method is:

int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());

But you should really try to use different folders resources for the countries that you want to support.


This is how to set an image into ImageView using the setImageResource() method:

ImageView myImageView = (ImageView)v.findViewById(;
// supossing to have an image called ic_play inside my drawables.


you use that code

ImageView[] ivCard = new ImageView[1];

protected void onCreate(Bundle savedInstanceState)  



you may try this:-


Leave a Reply

Your email address will not be published. Required fields are marked *