2

I've been having lots of troubles using adapter to display my images properly into my imageView. So basically I have a JSON string and I am parsing through it to get the url of each image. Then I want to display the each image with its title in a list view fashion.

I found this code online where it works perfectly when only one image needs to be displayed, but it doesn't work when I have to do this dynamically. Anyone has some good suggestions on how to get it to work? I attached parts of my codes for references.

Thank you!!!

 //results => JSON string
 ArrayList<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
 for(int i = 0; i < results.length(); i++){
 JSONObject c = results.getJSONObject(i);

// Storing each json item in variable
cover = c.getString(TAG_COVER);
String title = c.getString(TAG_TITLE);

try {

    URL urlS = new URL(cover);
    new MyDownloadTask().execute(urlS);

    }catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>(); 

// adding each child node to HashMap key => value
map.put(TAG_COVER, cover);
map.put(TAG_TITLE, title);
// adding HashList to ArrayList
resultList.add(map);
}
}
   } catch (JSONException e) {
e.printStackTrace();
  } 

/**
 * Updating parsed JSON data into ListView
 * */
ListAdapter adapter = new SimpleAdapter(this, resultList,
        R.layout.list_item,
        new String[] {TAG_TITLE}, new int[] {
        R.id.title});

setListAdapter(adapter);

And here is the image downloaded codes I found :

private class MyDownloadTask extends AsyncTask<URL, Integer, Bitmap> {
    @Override
    protected Bitmap doInBackground(URL... params) {
        URL url = params[0];
        Bitmap bitmap = null;
        try {
            URLConnection connection = url.openConnection();
            connection.connect();
            InputStream is = connection.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
            //is.close(); THIS IS THE BROKEN LINE
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return bitmap;
    }


    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap != null) {
            ImageView myImage = (ImageView) findViewById(R.id.list_image);
            myImage.setImageBitmap(bitmap);
        } else {
            Toast.makeText(getApplicationContext(), "Failed to Download Image", Toast.LENGTH_LONG).show();
        }

    }       
}
4

1 回答 1

1

有很好的图书馆调用AQuery。您可以使用它,只需编写 2 行代码即可轻松获取所有这些东西,此外,它还会为您缓存所有图像,特别是如果您在ListView

AQuery aq = new AQuery(activity);
aq.id(R.id.image).image(url, false, true);

我也觉得用起来会更好CustomAdapter。我不确定是否可以使用SimpleAdapter. 希望这会帮助你。

于 2012-12-01T06:19:15.747 回答