Romi
Romi

Reputation: 4921

How to use ProgressDialog to show background progress in android

to show a background process i used ProgressDialogBox.

My code is as

add_button.setOnClickListener(new OnClickListener() {


        public void onClick(View viewParam) {


            progressDialog = ProgressDialog.show(AddTicketActivity.this, "", "Loading...");

            new Thread() {

            public void run() {

            try{

            sleep(10000);

            } catch (Exception e) {

            Log.e("tag", e.getMessage());

            }

            progressDialog.dismiss();
            }

            }.start();

Its working fine. But the problem is progess shows for 10000 ms where as i want it to show untill my data is fetched/added. i mean it should be dependent on fetching/adding time.

i thought to do like it

public void onClick(View viewParam) {

progressDialog = ProgressDialog.show(AddTicketActivity.this, "", "Loading...");

Fetching data code here

progressDialog.dismiss();
}

But it dint work, does not show any progress bar.

How can i use it.

Thanks.

Upvotes: 1

Views: 3769

Answers (3)

Arnab Chakraborty
Arnab Chakraborty

Reputation: 7472

Well your code is fine :

public void onClick(View viewParam) {

    progressDialog = ProgressDialog.show(AddTicketActivity.this, "", "Loading...");

    // Fetching data code here
    // ...
    // Data Fetched

    progressDialog.dismiss();
}

This should work, as long as your are fetching the code in the same thread (although that might lead to an ANR. Consider using AsyncTask).

EDIT : Note that if you are fetching data in a separate thread, according to your logic you will show your progress dialog and then immediately close it.

Upvotes: 0

EnthuDeveloper
EnthuDeveloper

Reputation: 670

This way of progress bar is asynchronous. This might be helpful for u.

// class for displaying dialog box
class DialogTask extends AsyncTask<Void, Void, String> {

    protected String doInBackground(Void... urls) {
        return null;
    }

    @Override
    protected void onPostExecute(String result) {

        method to execute
        super.onPostExecute(result);
    }
}

Upvotes: 2

Paresh Mayani
Paresh Mayani

Reputation: 128428

I would suggest you to use AsyncTask with either ProgressDialog or ProgressBar.

  1. In onPreExecute() method, display the ProgressBar or make it visible again like: progressbar.setVisibility(View.VISIBLE);
  2. In doInBackground() method, perform the background task
  3. In onPostExecute() method, just hide the ProgressBar using the progressbar.setVisibility(View.INVISIBLE);

Upvotes: 0

Related Questions