Android gridview异步下载
我将的代码与代码结合使用。当我尝试从URL异步下载图像而不更改样本大小时,一切正常。但是,当我试图计算样本大小时,屏幕上没有显示任何内容(gridview)。我阅读了日志,发现所有的图片都下载正确。我用于图像下载的代码是下一个:Android gridview异步下载,android,multithreading,gridview,Android,Multithreading,Gridview,我将的代码与代码结合使用。当我尝试从URL异步下载图像而不更改样本大小时,一切正常。但是,当我试图计算样本大小时,屏幕上没有显示任何内容(gridview)。我阅读了日志,发现所有的图片都下载正确。我用于图像下载的代码是下一个: Bitmap downloadBitmap(String url) { final HttpClient client = AndroidHttpClient.newInstance("Android"); final HttpGet getReque
Bitmap downloadBitmap(String url) {
final HttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
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 {
inputStream = entity.getContent();
// get Device Screen Dimensions
DeviceProperties dimensions = new DeviceProperties(activity);
return
decodeBitmapFromResource(url, inputStream,
dimensions.getDeviceWidth(),
dimensions.getDeviceHeight());
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (IOException e) {
getRequest.abort();
Log.w(TAG, "I/O error while retrieving bitmap from " + url, e);
} catch (IllegalStateException e) {
getRequest.abort();
Log.w(TAG, "Incorrect URL: " + url);
} catch (Exception e) {
getRequest.abort();
Log.w(TAG, "Error while retrieving bitmap from " + url, e);
} finally {
if ((client instanceof AndroidHttpClient)) {
((AndroidHttpClient) client).close();
}
}
return null;
}
我用来解码的代码是:
public static Bitmap decodeBitmapFromResource(String url, InputStream is,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FlushedInputStream(is), null,
options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options , reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(new FlushedInputStream(is), null,
options);
}
当我同时使用第一个和第二个BitmapFactory.decodeStream时,就会出现问题。如果我只使用第二个,一切都可以,但实际上我没有做任何样品。有什么建议吗?我找它花了很多时间。输入流只能读取一次,然后就消失了
如果要进行双传递(一个用于边界,另一个用于选项),必须首先将输入流复制到临时文件(使用FileOutputStream),然后通过打开两个FileInputStream对该文件执行双传递。或者,您可以对客户端执行两次。execute()同样的尝试。第一个用于确定样本大小,第二个用于生成正确的位图。这样,您就不必存储整个文件。请立即关闭第一个Inputstream。使用byteArrayOutputStream是更好的解决方案吗?执行双过程的原因是通过分配大内存区域来避免OutOfMemory异常。如果如果你使用字节数组,你将分配内存。