Download Image using AsyncTask in Android
suggest changeThis tutorial explains how to download an image with AsyncTask. The example shows a progress dialog while the image downloads.
Understanding Android AsyncTask
AsyncTask runs background work and delivers the result on the UI thread. For an isolated UI job, such as downloading data to show in a list, AsyncTask is enough.
- Use AsyncTask for short operations (a few seconds at the most).
- A task is defined by 3 generic types, Params, Progress, and Result, and 4 steps:
onPreExecute(),doInBackground(),onProgressUpdate(), andonPostExecute(). onPreExecute()runs on the UI thread before background work starts.doInBackground()runs on a background thread. CallpublishProgress()to report progress, and return the result when the work is finished.onProgressUpdate()receives those progress values on the UI thread.onPostExecute()receives the value returned bydoInBackground().- The generic types are:
- Params, the parameters sent to the task when it executes.
- Progress, the progress units published during the background work.
- Result, the result of the background work.
- Use
Voidfor any type the task does not need. - Call
cancel(boolean)to cancel a running task.
Downloading image using Android AsyncTask
your .xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/downloadButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click Here to Download" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="Your image will appear here" />
</LinearLayout>
.java class
package com.javatechig.droid;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class ImageDownloaderActivity extends Activity {
private ImageView downloadedImg;
private ProgressDialog simpleWaitDialog;
private String downloadUrl = "http://www.9ori.com/store/media/images/8ab579a656.jpg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.asynch);
Button imageDownloaderBtn = (Button) findViewById(R.id.downloadButton);
downloadedImg = (ImageView) findViewById(R.id.imageView);
imageDownloaderBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new ImageDownloader().execute(downloadUrl);
}
});
}
private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return downloadBitmap(param[0]);
}
@Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
simpleWaitDialog = ProgressDialog.show(ImageDownloaderActivity.this,
"Wait", "Downloading Image");
}
@Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
downloadedImg.setImageBitmap(result);
simpleWaitDialog.dismiss();
}
private Bitmap downloadBitmap(String url) {
// initialize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttpGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
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 {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return null;
}
}
}
Since there is currently no comment field for examples (or I haven’t found it or I haven’t permission for it) here is some comment about this:
This is a good example what can be done with AsyncTask.
However the example currently has problems with
- possible memory leaks
- app crash if there was a screen rotation shortly before the async task finished.
For details see:
- http://stackoverflow.com/documentation/android/117/asynctask/14069/pass-activity-as-weakreference-to-avoid-memory-leaks
- http://stackoverflow.com/documentation/android/117/asynctask/5377/possible-problems-with-inner-async-tasks
- http://stackoverflow.com/documentation/android/2687/common-memory-leaks-and-how-to-avoid-them/9248/avoid-leaking-activities-with-asynctask
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents