marc3l
marc3l

Reputation: 2595

ProgressDialog in AsyncTask only displayed at the end of the task for a short time

I have a AsyncTask<Client, Void, Boolean> called LoginTask with a ProgressDialog, which you can see here. Now my problem is, if I launch this task with LoginTask(...).execute().get() the ProgressDialog is only shown very short at the end of the AsyncTask. Also I've put in some Thread.sleep(), but if I do that, I also get a ProgressDialog at the end of the Thread.

How can the ProgressDialog be displayed the whole async task?

    public class LoginTask extends AsyncTask<Client, Void, Boolean>
    {
      private ProgressDialog progressDialog;
      private MainActivity activity;

      public LoginTask(MainActivity activity)
      {
    this.activity = activity;
  }

  @Override
  protected void onPreExecute()
  {
    progressDialog = new ProgressDialog(activity);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage(activity.getText(R.string.asynctask_login_connect));
    progressDialog.setCancelable(false);
    progressDialog.show();
  }

  @Override
  protected Boolean doInBackground(Client... params)
  {
    try
    {
      Client client = params[0];
      if (client.connect())
      {
        progressDialog.setMessage(activity.getText(R.string.asynctask_login));
        if (client.manageHandshake())
        {
          return true;
        }
        else
          return false;
      }
      else
        return false;
    }
    catch (Exception e)
    {
      Log.e(LoginTask.class.getSimpleName(), "Can not handshake and connect to/with server.", e);
      return false;
    }
  }

  @Override
  protected void onPostExecute(Boolean result)
  {
    progressDialog.dismiss();
  }

}

Upvotes: 2

Views: 202

Answers (1)

Emmanuel
Emmanuel

Reputation: 13223

From the docs of the get(),

Waits if necessary for the computation to complete, and then retrieves its result.

This means that it will block the calling Thread until the execution is done; this defeats the whole purpose of using AsyncTask. Just call execute() and update the UI Thread from onPostExecute()

Upvotes: 2

Related Questions