Article
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
    LightSwitch
    iPhone/iPad
    Ruby on Rails
    IIS 7
    Windows 8
    CSS/CSS3
    Excel
    MS Access
    Shortcut Keys
    Visual SourceSafe
    Team Foundation Server
    API(s)
    Sencha-Touch
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog

Home >> Android >> Using AsyncTask in Android Application
Using AsyncTask in Android Application
Using AsyncTask in Android Application


by Rohit Kesharwani on 10/31/2011 9:49:20 PM

Views: 4339       Comments: 0

Using AsyncTask in Android Application

The class AsyncTask encapsulates the creation of Threads and Handlers. You must implement the method doInBackground (), which defines what action should be done in the background. This method is being automatically run in a separate Thread. To update the UI you can override the method onPostExecute (). This method will be called by the framework once your action is done and runs within the UI thread.

In this article I am going to explain how to use AsyncTask in an android application. In this example we will use AsyncTask to download the content of the webpage.

·         Start a new project named AsyncTaskDemo.

·         Open res/values/strings.xml and add the following element in the resources tag.

<string name="readWebpage">readWebpage</string>

·         Open AndroidManifest.xml and add the following permission:

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

·         Now set the layout of an application in the res/layout/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="match_parent"

    android:layout_height="match_parent">

       <Button android:layout_height="wrap_content"

                android:layout_width="match_parent"

                android:id="@+id/readWebpage"

                android:onClick="readWebpage"

                android:text="Load Webpage" />

       <TextView android:id="@+id/TextView01"

                  android:layout_width="match_parent"

                  android:layout_height="match_parent"

                  android:text="Example Text" />

</LinearLayout>

·         Open the Activity file and insert the following code:

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;

 

public class AsyncActivity 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) {

                                  e.printStackTrace();

                           }

                     }

                     return response;

              }

 

              protected void onPostExecute(String result) {

                     textView.setText(result);

              }

       }

 

       public void readWebpage(View view) {

              DownloadWebPageTask task = new DownloadWebPageTask();

              task.execute(new String[] { "http://www.google.co.in/" });

 

       }

}

·         Run the application.
The output should look like below:

Using AsyncTask in Android Application

When you click on the button (Load Webpage) the content of the website (google in this) will display in the TextView.

Report Abuse Form
Reason:    
 

Title :
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
     
 
Latest Article by Rohit KesharwaniRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Latest BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed ArticlesRSS Feed
    
    
    
    
    
    
    
    
    
    
Top Viewed BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
Latest Interview QuestionsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 2680
Advertisement
MindStick Cleaner
Advertise with Us
  
Copyright © 2013MindStick. All Rights Reserved.