Android Tutorials – Show a Progress Dialog while loading data

Sometimes you may need to run some logic for your app and you want the user to wait untill it is done. This means you should use a progress dialog. To update the progress dialog and run the logic at the same time it is obvious that you should use 2 threads. So we are going to use the main thread (or the ui thread) for the progress dialog update and a second thread for the logic:

	//inside the runnable will be the logic that you want to run
    void showProgressDialog(final Context context, final Runnable runnable) {
        final ProgressDialog ringProgressDialog = ProgressDialog.show(context, "Title ...", "Info ...", true);
        //you usually don't want the user to stop the current process, and this will make sure of that
        ringProgressDialog.setCancelable(false);
        Thread th = new Thread(new Runnable() {
            @Override
            public void run() {

                runnable.run();
                //after he logic is done, close the progress dialog
                ringProgressDialog.dismiss();
            }
        });
        th.start();
    }

Leave a Reply

You must be logged in to post a comment.