Emin Çiftçi
Emin Çiftçi

Reputation: 139

Get image from drawable dynamically

I am working on a barcode reader app and I want to show product image when the barcode read, so I renamed photos with product barcode numbers and put drawables folder. Photo name is for ex 1234567, try to retrieve with barcodeNo. But I got error on barcodeNo. How can i do this ?

ImageView iv = (ImageView) findViewById(R.id.imageView1);   
iv.setImageResource(R.drawable.barcodeNo);

Upvotes: 1

Views: 3377

Answers (3)

sirmagid
sirmagid

Reputation: 1130

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);
OR
imageview.setImageResource(imageResource)

Upvotes: 1

Asif Patel
Asif Patel

Reputation: 1764

@Narendra Sorathiya answer is right. you have write this code for solving the NullPointerException, which you posted on screenshot:

ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setImageResource(getImage(barcodeNo));
.
.
.
.
public int getImage(String imageName) {

     int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());

     return drawableResourceId;
}

Upvotes: 0

Narendra Sorathiya
Narendra Sorathiya

Reputation: 3830

just pass your code in getImage method to findout your image from drawable folder.

iv.setImageResource(getImage(barcodeNo));

public int getImage(String imageName) {

     int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());

     return drawableResourceId;
}

Upvotes: 1

Related Questions