Reputation: 178
In my Android App, I have an AsyncTask to Download a Picture from the Web and Show it in the UI (in onPostExecute() I'm generating a new ImageView). How can I make an AsyncTask which is downloading more than one Image at the same Time, and show the single Images directly when they are downloaded, even when the others aren't ready?
This is my Code:
public class DownloadImages extends
AsyncTask<Void, Void, Bitmap> {
@Override
protected Bitmap doInBackground(Void... params) {
Bitmap bitmap = null;
bitmap = downloadBitmap("HERE's MY URL");
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
ImageView image = new ImageView(context);
image.setImageBitmap(result);
((ViewGroup) planLinearLayout).addView(image);
}
}
public Bitmap downloadBitmap(String url) {
final AndroidHttpClient 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();
final Bitmap bitmap = BitmapFactory
.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException
// or
// IllegalStateException
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from "
+ url);
} finally {
if (client != null) {
client.close();
}
}
return null;
}
}
Upvotes: 1
Views: 8135
Reputation: 5626
Since you cannot make two requests at once, you can alternatively do the following:
Upvotes: 2
Reputation: 48592
I recommend to you to use the Universal Image Loader library to download the images in android.
It download the image as well do some more good things like caching the images and manage the memory very tricky.
If you do not want to cache the images then you can disable this feature using the Configuration
in the Universal Image Loader library.
Library links : https://github.com/nostra13/Android-Universal-Image-Loader
Upvotes: 1
Reputation: 8153
I would recommend Picasso, there you can use skipMemoryCache()
if you do not want images to be cached at all.
Upvotes: 1
Reputation: 12919
Just make use of onProgressUpdate(Progress...)
. Change your second generic type to Bitmap and call publishProgress()
after you have finished loading an image.
Upvotes: 1