How to set the image from drawable dynamically in android?

Android

Android Problem Overview


I am storing my project related images in drawable folder. Also I am storing the image names in string variable and dynamically I am trying to set those images to the imageview. But the image is not displaying. Please help me in this regard.

My Code:

int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(res);

In the above code "imagename" is the string variable which contains the image name.

Thanks in advance

Android Solutions


Solution 1 - Android

Try this:

String uri = "@drawable/myresource";  // where myresource (without the extension) is the file

int imageResource = getResources().getIdentifier(uri, null, getPackageName());

imageview= (ImageView)findViewById(R.id.imageView);
Drawable res = getResources().getDrawable(imageResource);
imageView.setImageDrawable(res);

Solution 2 - Android

Here i am setting the frnd_inactive image from drawable to the image

 imageview= (ImageView)findViewById(R.id.imageView);
 imageview.setImageDrawable(getResources().getDrawable(R.drawable.frnd_inactive));

Solution 3 - Android

imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(R.drawable.mydrawable);

Solution 4 - Android

Try this Dynamic code

String fnm = "cat"; //  this is image file name
String PACKAGE_NAME = getApplicationContext().getPackageName();
int imgId = getResources().getIdentifier(PACKAGE_NAME+":drawable/"+fnm , null, null);
System.out.println("IMG ID :: "+imgId);
System.out.println("PACKAGE_NAME :: "+PACKAGE_NAME);
//    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),imgId);
your_image_view.setImageBitmap(BitmapFactory.decodeResource(getResources(),imgId));

In above code you will need Image-file-Name and Image-View object which both you are having.

Solution 5 - Android

See below code this is working for me

iv.setImageResource(getResources().getIdentifier(
				"imagename", "drawable", "com.package.application"));

Solution 6 - Android

This works for me (dont use the extension of the image, just the name):

String imagename = "myImage";
int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(res);

Solution 7 - Android

Here is the best way that works in every phone at today. Most of those answer are deprecated or need an API >= 19 or 22. You can use the fragment code or the activity code depends what you need.

Fragment

//setting the bitmap from the drawable folder
Bitmap bitmap= BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.my_image);

//set the image to the imageView
imageView.setImageBitmap(bitmap);

Activity

//setting the bitmap from the drawable folder
Bitmap bitmap= BitmapFactory.decodeResource(MyActivity.this.getResources(), R.drawable.my_image);

//set the image to the imageView
imageView.setImageBitmap(bitmap);

Cheers!

Solution 8 - Android

set in ImageView like this : imageView.setImageResource(R.drawable.image)

Solution 9 - Android

imageView.setImageResource(R.drawable.picname);

Solution 10 - Android

getDrawable() is deprecated, so try this

imageView.setImageResource(R.drawable.fileName)

Solution 11 - Android

First of let's your image name is myimage. So what you have to do is that go to Drawable and save the image name myimage.

Now assume you know only image name and you need to access it. Use below snippet to access it,

what you did is correct , ensure you saved image name you are going to use inside coding.

public static int getResourceId(Context context, String name, String resourceType) {
	return context.getResources().getIdentifier(toResourceString(name), resourceType, context.getPackageName());
}

private static String toResourceString(String name) {
	return name.replace("(", "")
			   .replace(")", "")
			   .replace(" ", "_")
			   .replace("-", "_")
			   .replace("'", "")
			   .replace("&", "")
			   .toLowerCase();
}

In addition to it you should ensure that there is no empty spaces and case sensitives

Solution 12 - Android

As of API 22, getResources().getDrawable() is deprecated (see also https://stackoverflow.com/questions/29041027/android-getresources-getdrawable-deprecated-api-22). Here is a new way to set the image resource dynamically:

String resourceId = "@drawable/myResourceName"; // where myResourceName is the name of your resource file, minus the file extension
int imageResource = getResources().getIdentifier(resourceId, null, getPackageName());
Drawable drawable = ContextCompat.getDrawable(this, imageResource); // For API 21+, gets a drawable styled for theme of passed Context
imageview = (ImageView) findViewById(R.id.imageView);
imageview.setImageDrawable(drawable);

Solution 13 - Android

Here is how to do it in Kotlin, inside a loop i:

Code reused from rfsbraz 's answer

    val uri = "@drawable/pic_top${i+1}"
    val imageResource = activity.resources.getIdentifier(uri, null, activity.packageName)

    val res = activity.getResources().getDrawable(imageResource)
    holder.view.imgDigit.setImageDrawable(res)

Solution 14 - Android

getDrawable() is deprecated. now you can use

imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.msg_status_client_read)) 

Solution 15 - Android

ImageView imageView=findViewById(R.id.imageView)

if you have image in drawable folder then use

imageView.setImageResource(R.drawable.imageView)

if you have uri and want to display it in imageView then use

imageView.setImageUri("uri")

if you have bitmap and want to display it in imageView then use

imageView.setImageBitmap(bitmap)

note:- 1. imageView.setImageDrawable() is now deprecated in java 2. If image uri is from firebase or from any other online link then use

    Picasso.get()
    .load("uri")
    .into(imageView)

(https://github.com/square/picasso)

or use

Glide.with(context)
            .load("uri")
            .into(imageView)

(https://github.com/bumptech/glide)

Solution 16 - Android

This works fine for me.

final R.drawable drawableResources = new R.drawable(); 
final Class<R.drawable> c = R.drawable.class;
final Field[] fields = c.getDeclaredFields();
for (int i=0; i < fields.length;i++) 
{
     resourceId[i] = fields[i].getInt(drawableResources);  
    /* till here you get all the images into the int array resourceId.*/
}
imageview= (ImageView)findViewById(R.id.imageView);
if(your condition)
{
   imageview.setImageResource(resourceId[any]);
}

Solution 17 - Android

int[] phptr=new int[5];

adding image pointer to array

for(int lv=0;lv<3;lv++)
    {
        String id="a"+String.valueOf(lv+1);
        phptr[lv]= getResources().getIdentifier(id, "drawable", getPackageName());
    }

for(int loopvariable=0;loopvariable<3;loopvariable++) 
    {
        et[loopvariable] = findViewById(p[loopvariable]);
    }



for(int lv=0;lv<3;lv++)
    {
        et[k].setImageResource(phptr[k]);
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhemanth kumarView Question on Stackoverflow
Solution 1 - AndroidrfsbrazView Answer on Stackoverflow
Solution 2 - AndroidRam kiran PachigollaView Answer on Stackoverflow
Solution 3 - AndroidGeorgy GobozovView Answer on Stackoverflow
Solution 4 - AndroidChintan RaghwaniView Answer on Stackoverflow
Solution 5 - AndroidNiraliView Answer on Stackoverflow
Solution 6 - Androidcmcoffee91View Answer on Stackoverflow
Solution 7 - AndroidFaustino GagnetenView Answer on Stackoverflow
Solution 8 - AndroidsimpiView Answer on Stackoverflow
Solution 9 - AndroidKaran DatwaniView Answer on Stackoverflow
Solution 10 - AndroidemilpmpView Answer on Stackoverflow
Solution 11 - AndroidVenkyView Answer on Stackoverflow
Solution 12 - AndroidsohelpmeView Answer on Stackoverflow
Solution 13 - AndroidOsama RemlawiView Answer on Stackoverflow
Solution 14 - AndroidAbdul RizwanView Answer on Stackoverflow
Solution 15 - AndroidShashank PandeyView Answer on Stackoverflow
Solution 16 - AndroidParag KadamView Answer on Stackoverflow
Solution 17 - AndroidAnandView Answer on Stackoverflow