How To Show A Progress Dialog in Android

OVERVIEW

When you need to do some long running task and show a “wait” dialog to the user while the task is running, a Progress Dialog is the best way to go. When you do not know how long the task will take , then you show a Spinner instead of a horizontal progress bar. Here we will use the example of using a Spinner while authenticating a user after he has filled in a login form.

 

CODE

In our layout xml we called the doLogin() function when the Login button is clicked. This function will in turn execute an AsyncTask which will execute a backend process. The ProgressDialog will be shown before the AsyncTask starts execution and will go away once the AsyncTask has finished execution.

public class LoginActivity extends ActionBarActivity {

    ProgressDialog mProgressBar;

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

        mProgressBar = new ProgressDialog(this);
    }

 public void doLogin(View view) {
        mProgressBar.setCancelable(false);
        mProgressBar.setMessage("Authenticating your login..");
        mProgressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressBar.show();
        new LoginTask().execute(0);

    }
}

  //////////////////////////////////////////////////////////////////////////////

    //
    // The params are dummy and not used
    //
    class LoginTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected String doInBackground(Integer... params) {

                try {
                    Thread.sleep(2000);
                    // some long running task will run here. We are using sleep as a dummy to delay execution

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            return "Task Completed.";
        }
        @Override
        protected void onPostExecute(String result) {
            mProgressBar.hide();
            // do whatever needs to be done next
        }
        @Override
        protected void onPreExecute() {
        }
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

4 Comments

  1. @geethadevi,

    AsyncTask is a class which is used to execute long running processes. Mostly its used when data has to be sent or received from a URL or from a database. Android does not allow long running taskings to be called on the main thread as it will block the system event loop and the device will freeze. Calling AsyncTask does not block the main thread as the process runs on a background thread.
    You can find more details here: https://developer.android.com/reference/android/os/AsyncTask.html

Leave a Reply to piruzi Cancel reply

Your email address will not be published.


*