我在使用适配器将我的图像正确显示到我的 imageView 中时遇到了很多麻烦。所以基本上我有一个 JSON 字符串,我正在解析它以获取每个图像的 url。然后我想以 ListView 方式显示每个图像及其标题。
我在网上找到这段代码,当只需要显示一张图片时,它可以完美地工作,但当我必须动态地执行此操作时,它就不起作用了。有人对如何让它工作有一些好的建议吗?我附上了部分代码以供引用。
谢谢!!!
//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
的库。您可以使用它,只需编写 2 行代码即可轻松获得所有这些东西,而且它会为您缓存所有图像,这非常好,特别是如果您在 ListView
AQuery aq = new AQuery(activity);
aq.id(R.id.image).image(url, false, true);
另外我认为使用 CustomAdapter
会更好。我不确定是否可以使用 SimpleAdapter
来处理这种情况。
希望这对您有所帮助。
关于Android动态显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13656947/