How to create Progress Dialog in Android Application?

23,908

Solution 1

To show the prgress dialog you can use the below code

 ProgressDialog dialog = new ProgressDialog(MainActivity.this);
                dialog.setMessage("Your message..");
                dialog.show();

before you call the async task i.e. before new YourTask.execute().

and in the onPostExecute function of the asynctask You can use

 dialog.dismiss();

to dismiss the dialog.

Solution 2

You can use the fallowing method:

public void launchBarDialog(View view) {
    barProgressDialog = new ProgressDialog(MainActivity.this);

    barProgressDialog.setTitle("Downloading Image ...");
    barProgressDialog.setMessage("Download in progress ...");
    barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
    barProgressDialog.setProgress(0);
    barProgressDialog.setMax(20);//In this part you can set the  MAX value of data
    barProgressDialog.show();

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {

                // Here you should write your time consuming task...
                while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {

                    Thread.sleep(2000);

                    updateBarHandler.post(new Runnable() {

                        public void run() {

                            barProgressDialog.incrementProgressBy(1);//At this, you can put how many data is downloading by a time
                                                                     //And with the porcentage it is in progress
                        }

                    });

                    if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {

                        barProgressDialog.dismiss();

                    }
                }
            } catch (Exception e) {
            }
        }
    }).start();
}

Hopefully it works for you all.

Share:
23,908
shiteru
Author by

shiteru

Updated on July 15, 2022

Comments

  • shiteru
    shiteru almost 2 years

    I am developing the application to receive some data from the internet while receiving the data I want to show the "Progress Dialog". I used "AsyncTask" in my application.

    The question is how to use it and how to show the percentage like 100%?

    Please suggest me and give me some example. Thank you and Sorry for my English.