Wednesday, 26 August 2015

Android Programming Tutorials 12 : AsyncTask In Android

AsyncTask:

Before going to our topic of AsyncTask, Let me explain why we are using AsynTask in android.When we run our Project, all the methods of the Activity are executed starting from the onCreate() to onDestroy() all the method execution is take care by the Thread i.e.. Main Thread of our application.Instead we are getting ANR- Android Not RespondingException.This is because of only one main thread of our application can take care of all the work.



Android User Interface(UI) Main Thread:
Android handles input events with a single User Interface thread and the thread is called Main thread. Main thread cannot handle concurrent operations as it handles only one operation at a time.

Reason for ANR Exception or slow running tasks:
    1.   Accessing resources (Download any Song(MP3, Interacting With the Remote      Database etc..) from Internet
    2.   Database operations
    3.   Webservice calls
    4.   Complex logic that takes quite long time

AsyncTask? when to use?

AsyncTask is an abstract Android class which helps the Android applications to handle the Main UI thread in efficient way. AsyncTask class allows us to perform long lasting tasks/background operations and show the result on the UI thread without affecting the main thread.

Assume you have created a simple Android application which is interacting with the Remote database to fletching the data or file from Internet on launching the application.




onPreExecute:
Invoked before the task is executed ideally before doInBackground method is called on the UI thread. This method is normally used to setup the task like showing progress bar in the UI.
doInBackground:
Code running for long lasting time should be put in doInBackground method. When execute method is called in UI main thread, this method is called with the parameters passed.
onProgressUpdate:
Invoked by calling publishProgress at anytime from doInBackground. This method can be used to display any form of progress in the user interface.
onPostExecute:
Invoked after background computation in doInBackground method completes processing. Result of the doInBackground is passed to this method.

Let Work with any Example To Understand AsyncTask:

In this tutorial the AsyncTask will interact with the Remote database of and Fletch the data 

Create Android Application:
  •         File >> New >> Android Application
             Enter Project name: AsyncTaspApp
             Package: com.ambilpursunil.newapp
            Keep other default selections, click Next until you reach Finish


1.Simply Copy and Past the Code which is display below in the    MainActivity.java

package com.example.asynctaskapp;

import android.R;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;

public class MainActivity extends Activity{

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        new PostTask().execute("http://www.eenadu.com/latestnews");
            }
           
            public class PostTask extends AsyncTask<String,Integer, String>{
                       
                        @Override
                        protected void onPreExecute() {
                        // TODO Auto-generated method stub
                        super.onPreExecute();
                        displayProgressBar("Downloading.......");
                        }
                        @Override
                        protected String doInBackground(String... params) {
                        String url = params[0];
                        for(int i =0;i<=100;i+=5){
                        try{
                        Thread.sleep(50);
                        }catch(InterruptedException e){
                        e.printStackTrace();
                        }
                        publishProgress(i);
                        }
                        return "All Done";
                        }
                       
                        @Override
                        protected void onProgressUpdate(Integer... values) {
                        // TODO Auto-generated method stub
                        super.onProgressUpdate(values);
                        updateProgressBar(values[0]);
                        }
                       
                        @Override
                        protected void onPostExecute(String result) {
                        // TODO Auto-generated method stub
                        super.onPostExecute(result);
                         dismissProgressBar();
                        }
                       }

            public void displayProgressBar(String string) {
                        // TODO Auto-generated method stub
                       
            }

            public void dismissProgressBar() {
                        // TODO Auto-generated method stub
                       
            }

            public void updateProgressBar(Integer integer) {
                        // TODO Auto-generated method stub
                       
            }

}

2.Simple Copy and Past the below code:  actvitiy_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.asynctaskapp.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

3.Copy and past the code for  manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ambilpursunil.newapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

    <application
        android:allowBackup="true" 
        android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

    <activity 
       android:name="com.ambilpursunil.newapp.MainActivity"
       android:configChanges="keyboard|keyboardHidden|orientation>


   <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />

  </intent-filter>

       </activity>
  </application>
</manifest>

4.Right click on the project and Run As-->Android Application


OutPut:

When ever our application launch the it will be fletch the data and display

Stay Tune For Next Tutorial... SQlite Database in Android:

Please Send Your Comments To ambilpura.sunil@gmail.com

No comments:

Post a Comment