Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an Image to ImageView dynamically from a JSON array

I want to add an image to my iamgeview from the link stored in a JSON file that looks like this:

{
"parts":[
    {"name": "Bosch Iridium",

        ...
        ...
        ...

        "image": "R.drawable-hdpi.plug_boschi"
    },

Right now I pull the link and display it with this code:

try {

    jObject = new JSONObject(sJSON.substring(sJSON.indexOf('{')));
    JSONArray pluginfo = jObject.getJSONArray("parts");
    JSONObject e = pluginfo.getJSONObject(position);

    String imagefile = e.getString("image");
    Drawable image = getDrawable(imagefile);

    ImageView itemImage = (ImageView) findViewById(R.id.item_image);

    itemImage.setImageDrawable(image);

        } catch (JSONException e) {
        e.printStackTrace();
        }
    }

I'm pretty sure that this part is correct

ImageView itemImage = (ImageView) findViewById(R.id.item_image);

itemImage.setImageDrawable(image);

But I need help with the part above that which is getting the link from the JSON array so I can display it.

like image 241
Domenik VanBuskirk Avatar asked Dec 26 '22 14:12

Domenik VanBuskirk


1 Answers

You need to get first the resource ID from the string contained in the JSON.

String imagefile = e.getString("image");
String resName = imagefile.split("\\.")[2]; // remove the 'R.drawable.' prefix
int resId = getResources().getIdentifier(resName, "drawable", getPackageName());
Drawable image = getResources().getDrawable(resId);
like image 79
sdabet Avatar answered Mar 12 '23 06:03

sdabet