71

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

hemanth kumar
  • 2,881
  • 10
  • 35
  • 63

17 Answers17

127

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);
rfsbraz
  • 1,913
  • 1
  • 17
  • 26
  • 4
    hi i tried your code it is showing the error as android.content.res.Resources$NotFoundException: Resource ID #0x0 at line Drawable res = getResources().getDrawable(imageResource); plz help me – hemanth kumar Jul 31 '12 at 11:35
  • You need to change the uri for your image name. Like "@drawable/MYIMAGENAME.extension" – rfsbraz Jul 31 '12 at 11:37
  • my code:int imageResource = getResources().getIdentifier(image_url, null, getPackageName()); myimgview = (ImageView)findViewById(R.id.imageView); Drawable res111 = getResources().getDrawable(imageResource); myimgview.setImageDrawable(res111); – hemanth kumar Jul 31 '12 at 11:38
  • image_url contains the image name as "image.png" – hemanth kumar Jul 31 '12 at 11:39
  • image_url should contain "@drawable/image.png" – rfsbraz Jul 31 '12 at 13:13
  • 9
    It worked for me without png extension, with extension it was giving me error. So you can try without extension – Sharjeel Ahmed May 23 '14 at 12:03
  • working without giving extension(.png). with extension its giving error – jaimin Sep 04 '14 at 09:55
  • Without image extension its working good.Please remove the image extension from your code. Happy Coding :) – Priyanka Sep 24 '14 at 07:45
  • 4
    Why the extension is still in the comments? I lost time 'till I got it to work by removing the extension. Even though I upvoted your answer, please edit it. Happy Pi-day :) – dephinera Mar 14 '15 at 17:00
  • This is causing `FATAL EXCEPTION: java.lang.OutOfMemoryError: Failed to allocate a xxxxx byte...` on Android 5.0.x – Junior Mayhé Apr 05 '16 at 22:22
  • I was too getting #0x0 problem. when I initialized imageResource before "int imageResource = getResources().getIdentifier(uri, null, getPackageName());" it was solved. – Prashant Jan 27 '18 at 20:05
  • I could load an SVG XML file from drawable folder to image view using this method. – Lanil Marasinghe Mar 27 '18 at 09:32
42

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));
Ram kiran
  • 20,129
  • 14
  • 55
  • 74
34
imageview= (ImageView)findViewById(R.id.imageView);
imageview.setImageResource(R.drawable.mydrawable);
Pratik Butani
  • 51,868
  • 51
  • 228
  • 375
Georgy Gobozov
  • 13,239
  • 8
  • 67
  • 75
21

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.

Chintan Raghwani
  • 3,329
  • 4
  • 18
  • 32
8

See below code this is working for me

iv.setImageResource(getResources().getIdentifier(
                "imagename", "drawable", "com.package.application"));
Nirali
  • 12,335
  • 6
  • 35
  • 52
7

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);
khagler
  • 3,728
  • 26
  • 38
cmcoffee91
  • 121
  • 2
  • 7
6

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!

Faustino Gagneten
  • 1,968
  • 2
  • 21
  • 41
3
imageView.setImageResource(R.drawable.picname);
Karan Datwani
  • 410
  • 6
  • 6
3

getDrawable() is deprecated, so try this

imageView.setImageResource(R.drawable.fileName)
Chris Emerson
  • 10,735
  • 2
  • 27
  • 53
emilpmp
  • 1,404
  • 10
  • 25
  • This solution worked for me. To add, if you need to clear the ImageView, just do: `imageView.setImageResource(android.R.color.transparent)` https://stackoverflow.com/a/8243184/1657502 – Antônio Medeiros Oct 12 '17 at 03:46
3

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

Zahra
  • 1,222
  • 1
  • 6
  • 25
simpi
  • 31
  • 2
2

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

Venky
  • 10,964
  • 5
  • 46
  • 66
2

As of API 22, getResources().getDrawable() is deprecated (see also 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);
Community
  • 1
  • 1
sohelpme
  • 115
  • 2
  • 9
1

getDrawable() is deprecated. now you can use

imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.msg_status_client_read)) 
Abdul Rizwan
  • 3,293
  • 27
  • 30
0

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]);
}
Parag Kadam
  • 2,659
  • 4
  • 18
  • 39
  • resourceId[i] = fields[i].getInt(drawableResources); getting error in this line Caused by: java.lang.IllegalArgumentException: not a primitive field – Atiar Talukdar Feb 20 '17 at 07:35
0
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]);
    }
Anand
  • 51
  • 1
  • 2
0
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)

Shashank Pandey
  • 326
  • 2
  • 11
0

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)
O. Remlawi
  • 237
  • 3
  • 9