Android(Java)使用asynctask加载图像
@Override
protected String doInBackground(String... arg0) {
mNewsList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL);
try {
mNews = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mNews.length(); i++) {
JSONObject c = mNews.getJSONObject(i);
String image = c.getString(TAG_IMAGE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_IMAGE, image);
mNewsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
ListAdapter adapter = new SimpleAdapter(Home.this, mNewsList,
R.layout.news_list, new String[] {TAG_IMAGE},
new int[]{R.id.ivImage});
newsList.setAdapter(adapter);
}
如何使用asynctask加载图像
尝试使用惰性列表适配器,但不适合我的需求。
最佳答案
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}