Monday, February 24, 2020

AsyncTask with Progressbar Android Example

Now that you know what a AsyncTask is, we will use the Async Task to create a Progressbar updation example in Android.
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.
AsyncTask with Progressbar Android Example

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>
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
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>