1

I have the following code, which I got by looking at the sample on the Android developer documentation. However, it doesn't actually show the dialog. If I take the dismiss() call out, it displays the dialog AFTER the call to doLogin() finishes, and then never goes away. I don't need it to be fancy, I just want to display something while the request executes.

    ProgressDialog dialog = ProgressDialog.show(GameList.this, "", 
            "Connecting. Please wait...", true);

    int r = app.doLogin();

    dialog.dismiss();

doLogin() is a method that makes an HTTP request against the server and it returns a status code to indicate if the request was successful.

user634618
  • 3,573
  • 1
  • 24
  • 17
zachtib
  • 123
  • 2
  • 11
  • 1
    Check this out. http://stackoverflow.com/questions/3893626/how-to-use-asynctask-to-show-a-progressdialog-while-doing-background-work-in-andr – Robby Pond Mar 10 '11 at 17:18

1 Answers1

4

It's never a good idea to run HTTP requests on a main thread. Spin a worker thread, use a Handler to dismiss the dialog back in the UI thread. Something like this:

ProgressDialog dialog = ProgressDialog.show(GameList.this, "",              "Connecting. Please wait...", true); 

final Handler h = new Handler(); //will execute on the main thread

new Thread(new Runnable(){
public void run()
{
    app.doLogin();
    h.post(new Runnable()
    {
        public void run()
        {
              dialog.dismiss();
        }
    }
}
}).start();

The three-level nesting is not necessary, of course. Just trying to illustrate the technique here.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
  • Using an AsyncTask would be even more easier. – Flo Mar 10 '11 at 19:17
  • @Flo: AsyncTask's system of providing parameters is unwieldy and hostile to primitives. Who needs parameters when you get all that for free with closures. – Seva Alekseyev Mar 11 '11 at 20:38
  • I understand what you mean, but for an Android beginner a AsyncTask might be easier to understand as in my opinion it is more structured than the solution with a handler and a custom thread. – Flo Mar 13 '11 at 13:03