Tuesday, November 13, 2012

AsyncTask Android example | AsyncTask in Android

13 comments
In this tutorial you will learn how to use AsyncTask in your application. This AsyncTask class perform background operations and update the results on the UI

AsyncTask has three generic type
  • Params, the type of the parameters sent to the task upon execution.
  • Progress, the type of the progress units published during the background computation.
  • Result, the type of the result of the background computation

Private class ShowDialogAsyncTask extends 
        AsyncTask<Params, Progress, Result>{....}


AsyncTask goes through 4 steps

  • onPreExecute(),invoked on the UI thread immediately after the task is executed.
  •  doInBackground(Paaram ...),invoked on the background thread immediately after onPreExecute() finishes executing.
  • onProgressUpdate(Progress...) invoked on the UI thread after a call to publishProgress(Progress...).
  •  onPostExecute(Result), invoked on the UI thread after the background computation finishes. 


Android AcyncTask Example Android ProgressBar

AsyncTaskActivity


package com.javasrilankansupport.asynctask;

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


public class AsyncTaskActivity extends Activity {

 Button btn_start;
 ProgressBar progressBar;
 TextView txt_percentage;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task);
        
        btn_start = (Button) findViewById(R.id.btn_start);
        progressBar =  (ProgressBar) findViewById(R.id.progress);
        txt_percentage= (TextView) findViewById(R.id.txt_percentage);
        
        btn_start.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    
    btn_start.setEnabled(false);
    new ShowDialogAsyncTask().execute();
   }
  });
    }

    
    private class ShowDialogAsyncTask extends AsyncTask<Void, Integer, Void>{

     int progress_status;
     
     @Override
  protected void onPreExecute() {
   // update the UI immediately after the task is executed
   super.onPreExecute();
   
    Toast.makeText(AsyncTaskActivity.this,
            "Invoke onPreExecute()", Toast.LENGTH_SHORT).show();

    progress_status = 0;
    txt_percentage.setText("downloading 0%");
   
  }
     
  @Override
  protected Void doInBackground(Void... params) {
   
   while(progress_status<100){
    
    progress_status += 2;
    
    publishProgress(progress_status);
    SystemClock.sleep(300);
    
   }
   return null;
  }
 
  @Override
  protected void onProgressUpdate(Integer... values) {
   super.onProgressUpdate(values);
   
   progressBar.setProgress(values[0]);
   txt_percentage.setText("downloading " +values[0]+"%");
   
  }
  
  @Override
  protected void onPostExecute(Void result) {
   super.onPostExecute(result);
   
    Toast.makeText(AsyncTaskActivity.this,
            "Invoke onPostExecute()", Toast.LENGTH_SHORT).show();
    
    txt_percentage.setText("download complete");
    btn_start.setEnabled(true);
  }
    }
}


activity_async_task.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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:padding="@dimen/padding_medium"
        android:text="@string/async_task"
        tools:context=".AsyncTaskActivity" />

    <ProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="34dp" />

    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progress"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:minWidth="120dp"
        android:text="@string/start_btn" />

    <TextView
        android:id="@+id/txt_percentage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/progress"
        android:text="downloading  0%"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>



Download AsyncTask Android example


You may also like 


13 comments:

Unknown said...

Nice tutorial for basic AsyncTask Users..
But i want to do XML parsing and Downloading the images from the Network as a background opperation.. can u suggest me a code snippet please.

Chathura Wijesinghe said...

Thank you, already did this I will update soon. Refer this post to get idea about XML parsing How To Create XML File in JAVA - (DOM)

Dnyaneshwar Babar said...

This is my project error plz give answer

R cannot be resolved to a variable

Unknown said...

new ShowDialogAsyncTask().execute(); sir why we are using .execute here

Chathura Wijesinghe said...

@ DnyanuDada check your activity_layout.xml

Chathura Wijesinghe said...

@pavan ShowDialogAsyncTask().execute(); is execute the ShowDialogAsyncTask and onPreExecute(),invoked on the UI thread immediately after the task is executed

venkatesh said...

Post article on how to parse json data to a listview

Neo Heartnet said...

can help me with this code?
i tried to make toast on my login project but no
message toast out only error i got.. please help me.

here my code.



class BuatLogin extends AsyncTask {

/**
* Sebelum memasuki menu buat progres dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login_layout.this);
pDialog.setMessage("Login_layout Progress...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Konkesi
* */
protected String doInBackground(String... args) {
String usr = user.getText().toString();
String pwd = pass.getText().toString();

Log.d("1 "+usr, pwd);
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("usr", usr));
params.add(new BasicNameValuePair("pwd", pwd));
Log.d("2 "+usr, pwd);
Log.d(usr,url_create_login);

// getting JSON Object
// login url menerima POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_login,
"POST", params);

// cek log untuk response
Log.d("Buat Respond", json.toString());

// check untuk sukses tag
try {
int sukses = json.getInt(TAG_SUKSES);

if (sukses == 1) {
String nim=json.getString(TAG_NIM);
Log.d(TAG_NIM,nim);

// sukses login
Intent i = new Intent(getApplicationContext(), Mhs_main_layout.class);
i.putExtra(TAG_NIM, nim);
startActivity(i);

// tutup layar
finish();
} else if(sukses == 2) {
String nim=json.getString(TAG_NIM);
Log.d(TAG_NIM,nim);
Intent i = new Intent(getApplicationContext(), Admin_main_layout.class);
i.putExtra(TAG_NIM, nim);
startActivity(i);

// tutup layar ini
finish();
}else if(sukses == 3){

//>>>>>>> I tried to display this toast if fail to login but no message error only emulator said error
Toast.makeText(Login_layout.this, "Error Login...Silahkan Masukkan Nip/Nim Dan Password Anda", Toast.LENGTH_LONG).show();

}
} catch (JSONException e) {
e.printStackTrace();
}


return null;

}

protected void onPostExecute(String file_url) {
// dismiss dialog setelah selesai
pDialog.dismiss();
}



}
public void login(View theButton){


new BuatLogin().execute();

}

public void berhasil(View theButton){
Intent i = new Intent(getApplicationContext(), Register_layout.class);
startActivity(i);

}


}

Unknown said...

//try this

Toast.makeText(Login_layout.this, "Error Login...Silahkan Masukkan Nip/Nim Dan Password Anda", Toast.LENGTH_LONG).show());

Unknown said...

Hi there. A quick one. How do I run this while the intent front camera is on?

Unknown said...

1 word 'Awesome' tutorial ...
Great times Thanks, bro

Dev said...

Help make it happen for AndroidCodeGeeks - The Android Knowledge Base

Unknown said...

Mobile and Vehicle GPS Tracking

Post a Comment