Android Progress Dialog Example

This article contains examples about how to use android.app.ProgressDialog to create a progress popup window.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/cQI1mp2jEY8

1. ProgressDialog Creation Steps.

  1. Create a new ProgressDialog instance.
  2. Set progress bar style ( horizontal or spinner circle ).
  3. Set other progress dialog properties such as title, icon, message etc.
  4. Add OK, Cancel button and related listener code if needed.
  5. Create a background thread to do the background work.
  6. Update the progress bar status in background thread.

2. Android ProgressDialog Example.

2.1 Layout Xml File.

activity_progress_dialog.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:id="@+id/showProgressDialogButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Open Progress Dialog"/>

    <Button
        android:id="@+id/showIndeterminateProgressDialogButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Open Indeterminate Progress Dialog"/>

    <TextView
        android:id="@+id/progressDialogValueTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"/>

</LinearLayout>

2.2 Activity Java File.

ProgressDialogActivity.java

package com.dev2qa.example;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.os.Handler;

import java.text.DecimalFormat;

public class ProgressDialogActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_dialog);

        setTitle("dev2qa.com --- Progress Dialog Example");

        this.showProgressDialog();

        this.showIndeterminateProgressDialog();

    }

    // Create a ProgressDialog when button is clicked.
    private void showProgressDialog()
    {
        Button showProgressDialogButton = (Button)findViewById(R.id.showProgressDialogButton);
        showProgressDialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ProgressDialog progressDialog = new ProgressDialog(ProgressDialogActivity.this);

                // Set horizontal progress bar style.
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                // Set progress dialog icon.
                progressDialog.setIcon(R.drawable.message_new);
                // Set progress dialog title.
                progressDialog.setTitle("Waiting...");
                // The maxima progress value.
                progressDialog.setMax(100);
                // Whether progress dialog can be canceled or not.
                progressDialog.setCancelable(true);
                // When user touch area outside progress dialog whether the progress dialog will be canceled or not.
                progressDialog.setCanceledOnTouchOutside(false);

                // This text view is used to show progress related messages.
                final TextView progressDialogValueTextView = (TextView)findViewById(R.id.progressDialogValueTextView);

                // Add ok button listener code.
                progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // Get current progress value.
                                int currProgress = progressDialog.getProgress();

                                // Calculate and format progress percentage.
                                DecimalFormat df = new DecimalFormat("##.#%");
                                float percentage = (float)currProgress / (float)progressDialog.getMax();
                                String percentageStr = df.format(percentage);

                                // Show percentage.
                                progressDialogValueTextView.setText("Current percentage is " + percentageStr);
                            }
                        }
                );

                // Add cancel button listener code.
                progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                progressDialogValueTextView.setText("You canceled the progress.");
                            }
                        }
                );


                // Set progress dialog message.
                progressDialog.setMessage("This is a horizontal progress dialog.");

                // Popup the progress dialog.
                progressDialog.show();

                // Create a new thread object.
                Thread thread = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        int i = 0;
                        // Update progress bar every 0.3 second.
                        while (i < 100) {
                            try {
                                Thread.sleep(300);
                                // Update the progress value.
                                progressDialog.incrementProgressBy(1);
                                // Update the secondary progress value.
                                progressDialog.incrementSecondaryProgressBy(5);
                                i++;
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                        // Close and delete the dialog when the progress bar is finished
                        progressDialog.dismiss();
                    }
                });

                // Start the thread.
                thread.start();
            }
        });
    }

    // Create a indeterminate ProgressDialog when button is clicked.
    private void showIndeterminateProgressDialog()
    {
        Button showIndeterminateProgressDialogButton = (Button)findViewById(R.id.showIndeterminateProgressDialogButton);
        showIndeterminateProgressDialogButton.setOnClickListener(new View.OnClickListener() {

            private final int PROGRESS_TASK_COMPLETE = 1;

            // This text view is used to show progress related messages.
            final TextView progressDialogValueTextView = (TextView)findViewById(R.id.progressDialogValueTextView);

            // This is the task thread run in background.
            private Thread taskThread;

            // Record whether user cancel the dialog or not.
            private boolean userCancelDialog = false;

            // This Handler is used to handle message from child thread.
            Handler messageHandler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    if(msg.what==PROGRESS_TASK_COMPLETE)
                    {
                        progressDialogValueTextView.setText("Task Completed.");
                    }
                }
            };

            @Override
            public void onClick(View view) {
                // Each time initiate the boolean value.
                userCancelDialog = false;

                final ProgressDialog progressDialog = new ProgressDialog(ProgressDialogActivity.this);

                // Set horizontal progress bar style.
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                // Set progress dialog icon.
                progressDialog.setIcon(R.drawable.message_bookmark);
                // Set progress dialog title.
                progressDialog.setTitle("Waiting For Task Complete...");
                // Whether progress dialog can be canceled or not.
                progressDialog.setCancelable(true);
                // When user touch area outside progress dialog whether the progress dialog will be canceled or not.
                progressDialog.setCanceledOnTouchOutside(false);

                // Add cancel button listener code.
                progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // This text view is used to show progress related messages.
                                TextView progressDialogValueTextView = (TextView)findViewById(R.id.progressDialogValueTextView);
                                progressDialogValueTextView.setText("You canceled the progress.");

                                userCancelDialog = true;
                            }
                        }
                );

                // Set progress dialog message.
                progressDialog.setMessage("This is a circle progress dialog.\r\nTask will be completed in 3 seconds.");

                // Popup the progress dialog.
                progressDialog.show();

                // Create a new thread object.
                taskThread = new Thread(new Runnable() {

                    @Override
                    public void run() {

                        try {
                            Thread.sleep(3000);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                        // If not user cancel the dialog.
                        if(!userCancelDialog) {
                            // Send a message to let primary thread to update text view.
                            Message msg = new Message();
                            msg.what = PROGRESS_TASK_COMPLETE;
                            messageHandler.sendMessage(msg);
                        }

                        // Close and delete the dialog when the progress bar is finished
                        progressDialog.dismiss();
                    }
                });

                // Start the thread.
                taskThread.start();
            }
        });
    }
}

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.