我正在使用http://android-developers.blogspot.gr/2010/07/multithreading-for-performance.html的代码与http://developer.android.com/training/displaying-bitmaps/index.html代码的组合。当我尝试从网址下载图像异步而不更改样本大小的一切都没事。但是当我尝试计算样本大小时,屏幕上没有任何东西出现(gridview)。我读了logcat,我发现所有的图像都正确下载。我使用的图像下载的代码是下一个:gridview异步下载
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。如果我只使用第二个,那么一切都可以,但实际上我不做任何样本。任何建议?我失去了很多时间寻找它。
是否使用byteArrayOutputStream更好的解决方案? – userX
您进行双通道的原因是通过分配大内存来避免OutOfMemory异常一个。如果你使用一个字节数组,你将会分配内存。 – Budius
你是对的!谢谢。 – userX