Skip to content

Instantly share code, notes, and snippets.

@luca-bernardi
Created January 28, 2013 13:38
Show Gist options
  • Save luca-bernardi/4655560 to your computer and use it in GitHub Desktop.
Save luca-bernardi/4655560 to your computer and use it in GitHub Desktop.
Android's AsyncTask for download asynchronously an image from an URL and assign it to an ImageView
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
public class DownloadImageTask extends AsyncTask<URL, Void, Bitmap> {
private static final String LOG_E_TAG = "DownloadImageTask";
private final WeakReference<ImageView> containerImageView;
public DownloadImageTask(ImageView imageView) {
this.containerImageView = new WeakReference<ImageView>(imageView);
}
@Override
protected Bitmap doInBackground(URL... params) {
URL imageURL = params[0];
Bitmap downloadedBitmap = null;
try {
InputStream inputStream = imageURL.openStream();
downloadedBitmap = BitmapFactory.decodeStream(inputStream);
} catch (Exception e) {
Log.e(LOG_E_TAG, e.getMessage());
e.printStackTrace();
}
return downloadedBitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
ImageView imageView = this.containerImageView.get();
if (imageView != null) {
imageView.setImageBitmap(result);
}
}
}
@trinadhkoya
Copy link

when i make use of this.It is resulting the out of memory error and While Scrolling Images are reloading .There by it shows "Unfortunately app has beeen stopped"

@aroranubhav
Copy link

My stream returns an empty string to the bitmap, what might be the reason?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment