How to dynamically add image to ImageView from JSON array

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

{ "parts":[ {"name": "Bosch Iridium", ... ... ... "image": "R.drawable-hdpi.plug_boschi" }, 

Right now I am pulling the link and showing 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 am sure this part is correct.

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

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

+4
source share
2 answers

You need to first get the resource identifier from the string contained in 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); 
+9
source

What you want to do is look at the Resources class.

 getIdentifier (String name, String defType, String defPackage); 

So basically analyze the object to find plug_boschi text, and call:

 int resid=Context.getResources().getIdentifier ("plug_boschi", "drawable", null); 
0
source

Source: https://habr.com/ru/post/1446969/


All Articles