local image through local json in android
Let's imagine that you have some images in your drawable
folder:
drawable
image_name_1
image_name_2
image_name_3
image_name_4
...
Put the name of image to json:
[
{
"some_field_1": "some_value_1",
"some_field_2": "some_value_2",
"some_field_3": "some_value_3",
...
"image_name": "image_name_1"
},
{
"some_field_1": "some_value_1",
"some_field_2": "some_value_2",
"some_field_3": "some_value_3",
...
"image_name": "image_name_2"
},
{
"some_field_1": "some_value_1",
"some_field_2": "some_value_2",
"some_field_3": "some_value_3",
...
"image_name": "image_name_3"
},
...
]
Get name from JSON and load drawab resource:
JSONArray data; // your JSON
Context context; // context
Resources resources = context.getResources();
for (int i = 0; i < data.length(); i++) {
// getting some another JSON field
// get image name from JSON
String imageName = data.getJSONObject(i).getString("image_name");
// get resource id by image name
final int resourceId = resources.getIdentifier(imageName, "drawable", context.getPackageName());
// get drawable by resource id
Drawable drawable = resources.getDrawable(resourceId);
// get bitmap by resource id
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
}
Update
Put image resource id into HashMap
...
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
JSONArray data; // your JSON
Context context; // context
Resources resources = context.getResources();
for (int i = 0; i < data.length(); i++) {
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", "Country : " + countries[i]);
hm.put("cur","Currency : " + currency[i]);
// get image name from JSON
String imageName = data.getJSONObject(i).getString("image_name");
// get resource id by image name
final int resourceId = resources.getIdentifier(imageName, "drawable", context.getPackageName());
hm.put("flag", Integer.toString(resourceId) );
aList.add(hm);
}