0

I wanted to show a ProgressDialog when data need to be uploaded to the server.

I have checked this question Best way to show a loading/progress indicator? the best answer was

ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
// To dismiss the dialog
progress.dismiss();

when i tried to implement this in my code, nothing showed at all !! what is that i am doing wrong here?!

this is my code

private void UpdateData()
{

    ProgressDialog progress = new ProgressDialog(this);
    progress.setTitle("Loading");
    progress.setMessage("Wait while loading...");
    progress.show();

    try
    {
        UpdateWSTask updateWSTask = new UpdateWSTask();
        String Resp = updateWSTask.execute().get();

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

    progress.dismiss();

}

Community
  • 1
  • 1
asmgx
  • 7,328
  • 15
  • 82
  • 143

2 Answers2

4

The proper way of showing a ProgressDialog with a AsyncTask would be by displaying the dialog on the onPreExecute() method of the AsyncTask and hide it at onPostExecute() method of it:

 private class SampleTask extends AsyncTask<Void, Integer, String> {

     ProgressDialog progress = new ProgressDialog(YourActivity.this);

     protected Long doInBackground(Void... urls) {

        // execute the background task
     }

     protected void onPreExecute(){

     // show the dialog
        progress.setTitle("Loading");
        progress.setMessage("Wait while loading...");
        progress.setIndeterminate(true);
        progress.show();
     }

     protected void onPostExecute(String result) {
         progress.hide();
     }
 }

Both: onPreExecute() and onPostExecute() run on the main thread, while doInBackground() as the name suggests is executed on the background thread.

Edit: Within your activity, where you want to call the AsyncTask you just need to execute it:

UpdateWSTask updateWSTask = new UpdateWSTask();
updateWSTask.execute();
eldjon
  • 2,800
  • 2
  • 20
  • 23
0

A better idea would be to do this with AsyncTask class. You can take care of UI work in preExecute and postExecute methods and do your main work in doInBackground method. Nice and clean!

It seems that you already doing this. Move the dialog code to the asynctask class. You just need a reference to the context and you can provide it with a constructor for your custom asynctask class

Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • 2
    moving the dialog code inside the AsyncTask does not explain his problem – eldjon Aug 31 '14 at 14:34
  • "moving the code inside AsyncTask" would give the same result. "You need a reference to the context" has nothing to do with his problem. The method task.execute().get() was the problem causing the main thread to wait for the result of the background thread. – eldjon Aug 31 '14 at 17:32