Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Dealing HashMap.put for image

I want to add an image to the listview, how do i do so? The names and type are displaying properly. Currently stuck here.

.//other codes
.
.
try{
        JSONArray arr = new JSONArray(res);
        for(int i=0;i<arr.length();i++){                        
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject e = arr.getJSONObject(i);

            map.put("placeID", ""+ e.getString("placeID"));
            map.put("placeName",""+ e.getString("placeName"));
            map.put("placeType", ""+ e.getString("placeType"));
            map.put("image", R.drawable.ball_green);

            mylist.add(map);            
        }       
    }catch(JSONException e)        {
         Log.e("log_tag", "Error parsing data "+e.toString());
    }

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.places, 
                    new String[] { "placeName", "placeType" }, 
                    new int[] { R.id.placeName, R.id.placeType });
.
.
.//other codes

I want the image appropriately like:

ListView

like image 543
DroidMatt Avatar asked Aug 02 '26 06:08

DroidMatt


2 Answers

The R.java class is auto-generated at build-time and maintains a 'list' of integers which are resource ids. In other words R.<anything> is an Integer and doesn't directly represent the resource (string, drawable etc).

As your HashMap is expecting String types for both keys and values, you'll need to convert the ball_green resource id to a String. Example...

map.put("image", String.valueOf(R.drawable.ball_green));

In order to use it again you'll have to convert that String back to an Integer when using it to set the image of a widget such as an ImageView etc.

like image 186
Squonk Avatar answered Aug 03 '26 22:08

Squonk


I don't think adding image into a hashtable is a good idea. you can easily add a custom adapter, don't use SimpleAdapter.

like image 36
Sean Avatar answered Aug 03 '26 23:08

Sean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!