2
我一直有很多麻煩使用適配器來正確地顯示我的圖像到我的imageView。所以基本上我有一個JSON字符串,我通過解析來獲取每個圖像的URL。然後,我想以列表視圖的方式顯示每個圖像的標題。Android動態顯示圖像
我在網上發現了這個代碼,當它只需要顯示一個圖像時,它可以很好地工作,但當我必須動態地執行此操作時,它不起作用。任何人都有一些關於如何使其運行的好建議?我附上部分代碼以供參考。
謝謝!!!
//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);
這裏是圖像下載的代碼,我發現:
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();
}
}
}
AQuery非常棒。將它整合到我的圖書館。 – anticafe
Yeap這是非常好的) – Evos