Created
January 28, 2013 13:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
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
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"