Igal
Igal

Reputation: 6083

Setting ImageView source to an image from SQLite

I have a small SQLite DB in my project, where I have table "Products". One of the columns of this table is String "image". In the activity I receive a product id in the Intent extras, and create a Product object from the DB. In the layout of this activity I have an ImageView. Each time a Product object is created, I want to set the ImageView image to the one that is stored in the object. I tried to do the following:

ImageView product_image = (ImageView) findViewById(R.id.product_image);
product_image.setImageDrawable(Integer.parseInt("R.drawable."+productToPresent.getImage());

productToPresent is my Product object and getImage returns the image string name. However at this point my app crashes and I'm getting the following error message in the logcat:

RuntimeException: Unable to start activity ComponentInfo{com.myapp.appname/com.myapp.appname.ActivityProductDetails}: java.lang.NumberFormatException: Invalid int: "R.drawable.cat02_prod02" where cat02_prod02 is the string stored stored in my DB and the filename of the image.

So how can it be done?

Upvotes: 0

Views: 2278

Answers (1)

Goofy
Goofy

Reputation: 6128

You can do it in this manner:

int id = getResources()
       .getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);

This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following

imageview.setImageResource(id);

Upvotes: 2

Related Questions