Show ProgressDialog Android

Author: | Posted in Android, Quick Tips No comments

In this tutorial we will learn about how to use / show ProgressDialog android.

While performing some time taking tasks we need to show a loading indicator on screen like loading.., please wait.., etc. We can use built in android feature ProgressDialog,  it is easy to use loading indicator class used when we are performing a task that needs some time to execute for examples : Performing login/register in an android app, loading files/data from server, performing file processing, etc. the best approach to perform these tasks by using AsyncTask as we learned in our previous tutorial and AsyncTask gives us a feature to correctly show-hide ProgressDialog using its methods like (onPreExecute()) or (onPostExecute(Result)).

In (onPreExecute()) we can start showing ProgressDialog and in (onPostExecute(Result)) we can hide ProgressDialog.

Let’s start by creating  a ProgressDialog object like

 ProgressDialog pd = null; 

And place this code in (onPreExecute()) of AsyncTask

@Override
protected void onPreExecute() {
    super.onPreExecute();
    
    pd = new ProgressDialog(context);
pd.setTitle("Loading...");
    pd.setMessage("Please wait.");
    pd.setCancelable(false);
    pd.show();
    
}

Understanding the code

 pd = new ProgressDialog(context); 

This will create a instance of ProgressDialog.

 pd.setTitle("Loading..."); 

Used to set the title of ProgrssDialog.

 pd.setMessage("Please wait."); 

Used to set the message on ProgressDialog.

 pd.setCancelable(false); 

Setting this property to false will set it not able to cancel until programmatically called.

 pd.show(); 

To start showing created ProgressDialog above code is used.

After task execution to hide ProgressDialog we use

 pd.dismiss(); 

but it is safe to first check the state of pd object.

Write this code in (onPostExecute()) of AsyncTask

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
            
    if (pd != null) {
        if (pd.isShowing()) {
            pd.dismiss();
        }
        pd = null;
    }
            
}

this will close/hide the ProgressDialog.
We can also call pd.cancel(); to hide ProgressDialog it will work same as dismiss(); but the difference is it also calls ProgressDialog‘s OnCancelListener method.
So if we want to execute some code on cancel of ProgressDialog we can use it’s OnCancelListener.

Final output of our class will look like

    class LoadBackgroudData extends AsyncTask<String, String, String> {
        ProgressDialog pd;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(getBaseContext());
            pd.setTitle("Loading...");
            pd.setMessage("Please wait.");
            pd.setCancelable(false);
            pd.show();
        }
        @Override
        protected String doInBackground(String... params) {
            // execute your time taking process here
            return null;
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (pd != null) {
                if (pd.isShowing()) {
                    pd.dismiss();
                }
            }
        }
    }

Some times we need to show download/upload progress,we can use horizontal style ProgressDialog and setting by a maximum value as,

 
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
pd.setMax(100);

We will update ProgressDialog in AsyncTask‘s onProgressUpdate() method as

@Override
public void onProgressUpdate(Integer... args){
pd.setProgress(args[0]);
}

By publishing progress value from doInBackground() method like

publishProgress((int) progress);

The implementation of above code and final output of our class will lokk like

    class LoadBackgroudData extends AsyncTask<String, String, String> {
        ProgressDialog pd;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(getBaseContext());
            pd.setTitle("Loading...");
            pd.setMessage("Please wait.");
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pd.setMax(100);
            pd.setCancelable(false);
        }
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL("your_webservice_url");
                URLConnection connection = url.openConnection();
                connection.connect();
                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int length = connection.getContentLength();
                // downlod the file
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(
                        "/sdcard/file_name.file_extension");
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int) (total * 100 / length));
                    output.write(data, 0, count);
                }
                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {
            }
        }
        @Override
        protected void onProgressUpdate(String... values) {
            pd.setProgress(args[0]);
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (pd != null) {
                if (pd.isShowing()) {
                    pd.dismiss();
                }
            }
        }
    }

Hope it will help you guys to make use of ProgressDialog in your own Application’s.