jasonflaherty
jasonflaherty

Reputation: 1944

Is there a way to Download Image from URL within For Loop add to Hashmap Array?

I have a hashmap array I am putting info into from an XML file. How should I download the image to make it available in my listview?

Here is my code:

public void dealsCb(String url, XmlDom xml, AjaxStatus status) {

        List<XmlDom> products = xml.tags("Product");
        List<HashMap<String, String>> titles = new ArrayList<HashMap<String, String>>();

        for (XmlDom product : products) {
            HashMap<String, String> hmdata = new HashMap<String, String>();
            hmdata.put("title", product.text("Product_Name"));
            hmdata.put("desc", product.text("Sale_Price"));

            //NEED TO DOWNLOAD IMAGE FROM THIS URL AND THEN ADD TO ARRAY....
            hmdata.put("thumb", product.text("Image_URL"));

            titles.add(hmdata);
        }

        String[] from = { "thumb", "title", "desc" };

        int[] to = { R.id.icon, R.id.title, R.id.desc };

        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), titles,
                R.layout.activity_deals_item, from, to);

        ListView listView = (ListView) findViewById(R.id.list);

        listView.setAdapter(adapter);

    }

I have tried a method that gets the image, makes it a bitmap, then converts it to a drawable, but am no able to add it to the array since hmdata.put takes a string... What am I missing with the image loading?

Upvotes: 1

Views: 195

Answers (1)

Gunnar Hoffman
Gunnar Hoffman

Reputation: 1226

I think your best bet would be to create a new object that can contain all of the elements you are interested in using.

You should create a new object called "Product" that takes a XmlDom for its constructor and has getters for "title", "desc", and "thumbnail". These getters would return String, String, and Bitmap respectively.

You should be able to download images using an HttpClient or some similar android networking client: HttpClient

Once the image is downloaded you can use the BitmapFactory to convert it to a bitmap for use with an ImageView.

You can then add the custom "Product" object into a list for latter use.

Example:

public class Product{

   String title;
   String desc;
   Bitmap image;

   public Product(XmlDom x){ 
        ... download image, and assign to instance variables ... 
   }

   public String getTitle(){ return this.title; }

   ... more getters ...
}

Upvotes: 2

Related Questions