AsyncTask with Progressbar Example | AndroidMonks

 AsyncTask with Progressbar with Example

According to the Android Docs, “AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers”.

Now that you know what a AsyncTask is, we will use the Async Task to create a Progressbar updation example in Android.

YOU ARE YOUR BOSS
I agree to have my personal information transfered to MailChimp ( more information )
Join over 5.000 visitors who are receiving our free content and learn how to program with Android. The growth of Android is estimated to reach a whooping 83% by 2020. Hop on the train and start making money!
We hate spam. Your email address will not be sold or shared with anyone else.

This tutorial is not aimed to explain what a Async Task is, you can refer here for complete basic implementation of a AsyncTask and the need for it.

Creating the Layout

We are looking to create a ProgressBar and use that in our AsyncTask to update. We will be making use of the 4 callback methods in a AsyncTask class.

Check below for a simple Progressbar being created.

<ProgressBar
    android:id="@+id/progressBar"
    style="@style/CustomProgressBarHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:progress="40"/>

I have created a custom progressbar style in my style.xml class like below.

<style name="CustomProgressBarHorizontal" parent="android:Widget.ProgressBar.Horizontal">
    <item name="android:minHeight">10dip</item>
    <item name="android:maxHeight">20dip</item>

This handles my height so that i don’t have a huge ProgressBar in my activity.

Now that we have created the Progressbar in the Layout, let’s create a simple Class to handle our Async Task operation.

Creating a Activity with AsyncTask Class

Name the Activity as MainActivity.java like below.

public class AsyncTaskActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.async_task);
    }
}

A very simple Activity holding our async_task layout. It is time to create our AsyncTask class inside our Activity.

It is pretty easy to create a Async Task, you make use of the AsyncTask class and create a private class like below.

class MyTask extends AsyncTask<Integer, Integer, String>

This auto suggests overriding the 4 callbacks we saw above. They are,

  • doInBackground() – Operation to do (This is mostly where our action is done)
  • onPostExecute() – Things to do after the doInBackground task ends
  • onPreExecute() – Things to do before the doInBackground task
  • onProgressUpdate() – Callback that updates the progress.

In order to get clearer understanding of what a params, progress, result fields are check here.

We will create the Progressbar object and use that to update the progress in the background. The entire AsyncTaskActivity.java looks like this below

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ProgressBar;

public class AsyncTaskActivity extends AppCompatActivity {
    ProgressBar progressBar;
    int count = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.async_task);
        progressBar = findViewById(R.id.progressBar);
        new MyTask().execute(10);
    }

    class MyTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected String doInBackground(Integer... params) {
            for (; count <= params[0]; count++) {
                try {
                    Thread.sleep(1);
                    publishProgress(count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "Task Completed.";
        }
        @Override
        protected void onPostExecute(String result) {
            Log.d("Over","Over");

        }
        @Override
        protected void onPreExecute() {

            progressBar.setProgress(0);
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.d("Progress", String.valueOf(values[0]));
            progressBar.setProgress(values[0]);
        }
    }
}

In the above Activity, we have created a new Object for MyTask and called execute with the params. This value is used to wait and update the Progressbar in the background.

We can perform any operation we need in the main thread while this background task is happening through the Async Task.

Here is a complete Layout implementation for the async_task.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ProgressBar
        android:id="@+id/progressBar"
        style="@style/CustomProgressBarHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:progress="40"/>
</LinearLayout>

Once done, your application looks like below.

"<yoastmark

This simple tutorial can be extended to perform any action with AsyncTask in mind.

Drop in any comments you have below.

“Learn and be curious”

Also Read  5 Alternatives to SlidingDrawer with example

Leave a Comment

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