zachtib
zachtib

Reputation: 123

How do I show a ProgressDialog while an HttpRequest executes on Android?

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.

Upvotes: 1

Views: 1691

Answers (1)

Seva Alekseyev
Seva Alekseyev

Reputation: 61378

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.

Upvotes: 4

Related Questions