Android AsyncTask

AsyncTask is a one of the painless thread in android.AsyncTask will perform operation in backgroud and publish result to main UI thread.It won't affect main UI thread life cycle and run as a seperate thread.

AsyncTasks should ideally be used for short time operations . If you need to keep threads running for long periods of time, it is highly recommended you use the  Executor, ThreadPoolExecutor and FutureTask. 

AsyncTask consist of four methods :

onPreExecute()


            It is invoked on the UI thread before the task is executed. 

doInBackground(Params...)


            It is invoked on the background thread immediately after onPreExecute() finishes executing. 

onProgressUpdate(Progress...)


            It is invoked on the UI thread after a call to publishProgress(Progress...).

onPostExecute(Result)


            invoked on the UI thread after the background computation finishes.

You can download source code here.

1.Create a new project named AsyncTaskDemo.
2.Open the res/layout/activity_async_task.xml file and insert the following:

<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=".AsyncTaskActivity" >

    <TextView
        android:id="@+id/val"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

3.Open AsyncTaskActivity.java and insert the following code:

package com.etr.asynctaskdemo;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class AsyncTaskActivity extends Activity {

Boolean isInternetConnected = false;
JSONObject json;
ArrayList<String> names = new ArrayList<String>();
TextView view;
NetWorkStatus status;

@Override
protected void onCreate(Bundle savedInstanceState) {

try {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
view = (TextView) findViewById(R.id.val);

status = new NetWorkStatus(AsyncTaskActivity.this);
isInternetConnected = status.isConnecting();
if (isInternetConnected) {

new Invoke().execute();

} else {

showAlertDialog(AsyncTaskActivity.this,
"No Internet Connection",
"You don't have internet connection.", false);

}

} catch (Exception e) {
Log.v("Exception", Log.getStackTraceString(e));
}

}

public class Invoke extends AsyncTask<Void, Void, Void> {

JsonParser jsonParser = new JsonParser();
ProgressDialog dialog;

protected void onPreExecute() {
dialog = new ProgressDialog(AsyncTaskActivity.this);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
}

protected Void doInBackground(Void... arg0) {
String URL = "http://192.168.3.136:28080/logic/services/ListHolidays";
/* Make JSON Request */
final String body = String.format(
"{\"userName\": \"%s\", \"password\": \"%s\"}",
"Administrator", "admin");
try {
json = jsonParser.makeHttpRequest(URL, "POST", body);
JSONArray arr = json.getJSONArray("holidayBean");
for (int i = 0; i < arr.length(); i++) {
names.add(arr.getJSONObject(i).getString("name"));
}
Thread.sleep(10000);
} catch (Exception e1) {
Log.v("JSONCall Exception", Log.getStackTraceString(e1));
}
return null;
}

protected void onPostExecute(Void name) {
view.setText(names.size() + "  " + "record found");
dialog.dismiss();
}

}

public void showAlertDialog(Context context, String title, String msg,
Boolean status) {
AlertDialog.Builder builder = new AlertDialog.Builder(
AsyncTaskActivity.this);
builder.setTitle(title).setMessage(msg).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

Comments

Popular posts from this blog

SQLiteDatabase With Multiple Tables

Programmatically turn ON/OFF WiFi on Android device

Android Service and IntentService