Using Asynchronous task in Android

By | December 15, 2011

Hello all,

Today I will show you a demo on how to use Asynchronous task in android. You should use this if you are doing a task that takes longer time to complete.
This class doesnot block the UI thread so the “Application Not Responding” dialog will not appear when you are doing a big task.
You should subclass the Asynchronous class to use it and pass to this function “doInBackground” the parameters.
You can access the UIThread in the “onPostExecute” method.
Please check this example.
Here is the main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<Button
	android:layout_height="wrap_content"
	android:layout_width="fill_parent"
	android:id="@+id/readWebpage"
	android:onClick="readWebpage"
	android:text="Load Webpage">
</Button>
<TextView
	android:id="@+id/TextView01"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:text="Asynchronous task Demo from CoderzHeaven">
</TextView>
</LinearLayout>

Here is the AndroidManifest.xml file
Make sure to add the android.permission.INTERNET permission in this file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AsynsTaskExample"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

The main java file

package com.pack.coderzheaven;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class AsynsTaskExample extends Activity {
	private TextView textView;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		textView = (TextView) findViewById(R.id.TextView01);
	}

	private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = "";
			for (String url : urls) {
				DefaultHttpClient client = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(url);
				try {
					HttpResponse execute = client.execute(httpGet);
					InputStream content = execute.getEntity().getContent();

					BufferedReader buffer = new BufferedReader(
							new InputStreamReader(content));
					String s = "";
					while ((s = buffer.readLine()) != null) {
						response += s;
					}

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(),"Some Error Occurred! " + e.getMessage(), Toast.LENGTH_LONG).show();
				}
			}
			return response;
		}

		@Override
		protected void onPostExecute(String result) {
			textView.setText(result);
			Toast.makeText(getApplicationContext(),"Loading WebPage Complete", Toast.LENGTH_LONG).show();
		}
	}

	public void readWebpage(View view) {
		DownloadWebPageTask task = new DownloadWebPageTask();
		task.execute(new String[] { "http://www.google.com" });

	}
}

One thought on “Using Asynchronous task in Android

Leave a Reply to Mayaa Cancel reply

Your email address will not be published. Required fields are marked *