I am using the code of http://android-developers.blogspot.gr/2010/07/multithreading-for-performance.html in combination with http://developer.android.com/training/displaying-bitmaps/index.html code. when i try to download the images from urls asynchronously without change the sample size everything it is ok. But when i try to calculate the sample size nothing appears on the screen(gridview). I read the logcat and i see that all the images are downloaded correctly. the code that i am using for the image download is the next one:
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;
}
and the code i am using for decoding is this:
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);
}
the problem appears when i use the both the first and the second BitmapFactory.decodeStream. If i use only the second one everything it is ok but actually i don’t make any sample. Any suggestion? I have lost a lot of time looking for it.
A InputStream can only be read ONCE, then it is gone.
If you want to make a dual pass (one for just the bounds and the second to have the options, you must first copy the input stream to a temporary file (using a FileOutputStream) and then do the dual pass on that file by opening two FileInputStream.