【发布时间】:2015-10-06 06:45:18
【问题描述】:
我需要从服务器获取图像并将其加载到图像按钮。应用程序片段启动时动态加载的图像超过 50 个。最好的方法是什么。目前我正在使用以下代码,当我运行它时,应用程序卡住了,我也跟着Android Loading Image from URL (HTTP)教程,但是当有多个图像时它不显示图像。
这是我当前正在使用的代码,但应用程序正在冻结
private void setListParentItemInfo(View convertView,final IPTVChannel iptvChannel){
ImageButton logoBtn = ((ImageButton) convertView.findViewById(R.id.channelLogo));
String image_url="http://Channel.com.au/ChannelLogos/"+Channel.getLogoName();
logoBtn.setImageBitmap(downloadBitmap(image_url));
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return null;
}
我该如何解决这个问题或任何其他为什么要这样做?
【问题讨论】:
-
我推荐使用Picasso Library
-
本教程将帮助你实现毕加索库Working with Android image library Picasso