How to use AsyncTask in Android
Hi Friends,
In this blog post i am going brief about, AsyncTask in Android.
Why do we use AsyncTask?
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads.
AsyncTask class allows us to perform long lasting tasks/background operations and show the result on the UI thread without affecting the main thread.
How to use AsyncTask?
Let’s see one small application for downloading image in background from server and display the image in ImageView in android.
Step 1:
Give user permission for accessing the internet in Android Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
Step 2:
Include the following Xml file in your layout folder:
<?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/button" 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" > </ImageView> </LinearLayout>
Step 3:
Inlcude the foll0ing class in your source folder:
package com.example.asyntaskdemo; 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 MainActivity extends Activity { private ImageView downloadedImg; private ProgressDialog simpleWaitDialog; private String downloadUrl = "http://www.geeks.gallery/wp-content/uploads/2014/12/geeks.gallery.png"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button imageDownloaderBtn = (Button) findViewById(R.id.button); downloadedImg = (ImageView) findViewById(R.id.imageView); imageDownloaderBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new ImageDownloader().execute(downloadUrl); } }); } private class ImageDownloader extends AsyncTask<String,Bitmap,Bitmap> { //Display the Dialog box once the download gets started @Override protected void onPreExecute() { simpleWaitDialog = ProgressDialog.show(MainActivity.this, "Wait", "Downloading Image"); } //Download the image from server protected Bitmap doInBackground(String... param) { return downloadBitmap(param[0]); } //Display the image in ImageView once the download get completed protected void onPostExecute(Bitmap result) { downloadedImg.setImageBitmap(result); simpleWaitDialog.dismiss(); } private Bitmap downloadBitmap(String url) { final DefaultHttpClient client = new DefaultHttpClient(); 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 { // 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) { getRequest.abort(); Log.e("ImageDownloader", "Something went wrong while" + " retrieving bitmap from " + url + e.toString()); } return null; } } }
ScreenShots
Hope this blog post was helpful. Do let me know your feedback.
Related Posts
Nithya Govind
Latest posts by Nithya Govind (see all)
- How to Display Image Gallery Using ViewPager in Android - April 12, 2015
- How to Display Google Map in Android - February 19, 2015
- How to List Drawable Images in Array XML in Android using TypedArray - February 18, 2015