Using Progressbar with AsyncTask Android

buraknalpara.com

What is Progressbar ?

Progressbar is a component that displays the status of a synchronous or asynchronous process. In this example I will show you how to use progressbar with async task in android.

What is Asynctask in Android ?

AsyncTask is used for performing long tasks or background operations without affecting the main work. For example you are on a page and asked for a data from database or internet and by using async task you can fetch that data while continue surfing on the current page.

3 important methods to use progress bar

After creating and defining progress bar in your application you have to use some methods to make progress bar alive.

  • setIndeterminate(bool indeterminate)

This method indicates that our progress bar is measurable or not. In our case we know when it is going to finish because we are going to define that’s why we will configure it as false.

  • setMax(int max)

This method is used for to define maximum value of our progress bar. In our case it will be 10 because I didn’t want it take too much time.

  • setProgress(int progress)

This method is for setting the current status of progress bar. Since we want our progress bar to start from 0, I have defined it 0 at first. Later on we will update it.

The sample application

Our will application contains 1 imageview(you don’t have to add this), 1 progressbar and 1 button. The mission of the button is triggering the progress bar. It is very simple application.

Design of the application

As I said before we will have only 1 imagevew, 1 progressbar and 1 button in our layout file. Here is the code for activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:layout_editor_absoluteY="81dp">

    <ProgressBar
        android:id="@+id/progressBar"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="27dp"
        android:layout_marginEnd="58dp"
        android:layout_marginStart="58dp"
        app:layout_constraintBottom_toTopOf="@+id/btnStart"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="164dp"
        android:onClick="start"
        android:text="Start"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/progressBar" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="27dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toTopOf="@+id/progressBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/logo" />

</android.support.constraint.ConstraintLayout>
Codes of the application

After creating new new android project we already have MainActivity.java class. I have also created another class which name is AsyncTask.java. In this class I have written our Async codes because I did not want to write it inside our MainActivity class. It is important in case of readability. First let’s look at our MainActivity.java class codes.

public class MainActivity extends AppCompatActivity {
    ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progressBar = findViewById(R.id.progressBar);

        progressBar.setIndeterminate(false);
        progressBar.setProgress(0);
        progressBar.setMax(10);
    }

    public void start(View view){
        AsyncTask task = new AsyncTask();
        task.setProgressBar(progressBar);
        task.execute(10);
    }
}

I have defined our progress bar under OnCreate method and set the public methods for progress bar. I also have “start” function which is our buttons onClick function. In this start function we are calling our AsynTask class and executing it.

Next, let’s look at our AsyncTask class codes.

public class AsyncTask extends android.os.AsyncTask<Integer, Integer, String> {

    ProgressBar pb;
    int status = 0;

    public void setProgressBar(ProgressBar progressBar) {
        this.pb = progressBar;
    }

    @Override
    protected String doInBackground(Integer[] objects) {
        for (int i = 0; i < objects[0]; i++){
            status++;
            try {
                publishProgress(status);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer[] values) {
        pb.setProgress(values[0]);

        super.onProgressUpdate(values);

    }
}

Here we setProgress function which is used for assigning our progress bar in MainActivity class to the progress bar we have defined inside AsyncTask class. doInBackground is for what this async method will do in background and onProgressUpdate method is used for updating our progress bars status. Basically this application will count to 10 and fill the progress bar one by one each second.

Images of the application

Below are the images for our sample application using progress bar with async task.

progress bar with async task
Progress bar
progress bar with async task
progress bar progressing

Source Code of Using Progressbar with AsyncTask Android

Please see https://github.com/brknlpr/AsyncProgressBar

HBN

5 (100%) 5 votes

You May Also Like

About the Author: HBN

--Senior QA Engineer-- --Intermediate Web Developer-- --Junior Android Developer--

Leave a Reply

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