How to use AsyncTask to show a ProgressDialog while doing background work in Android? [duplicate]

Place your ProgressDialog in onPreExecute, sample code below:

private ProgressDialog pdia;

@Override
protected void onPreExecute(){ 
   super.onPreExecute();
        pdia = new ProgressDialog(yourContext);
        pdia.setMessage("Loading...");
        pdia.show();    
}

@Override
protected void onPostExecute(String result){
   super.onPostExecute(result);
        pdia.dismiss();
}

and in your onClickListener, just put this line inside:

new EfetuaLogin().execute(null, null , null);

The final solution which worked is taking all the code from OnClickListener to doInBackground method from AsyncTask implementation. Now the code is like:

OnClickListener:

OnClickListener loginListener = new OnClickListener() {
        public void onClick(View v) {
            /* Translation note: Original text: "Executando OnClickListener" */
            Log.d(TAG, "OnClickListener has been called");

            /* Translation note: Original text: "faz chamada assincrona" */
            // Make an asynchronous call
            new EfetuaLogin().execute();
        }
    }; 

All the work happens in EfetuaLogin AsyncTask implementation:

class EfetuaLogin extends AsyncTask<Object, Void, String> {

        private final static String TAG = "LoginActivity.EfetuaLogin";

        protected ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            Log.d(TAG, "Executando onPreExecute de EfetuaLogin");
            //inicia diálogo de progresso, mostranto processamento com servidor.
            progressDialog = ProgressDialog.show(LoginActivity.this, "Autenticando", "Contactando o servidor, por favor, aguarde alguns instantes.", true, false);
        }


        @SuppressWarnings("unchecked")
        @Override
        /* Translation note: Original text: "Object... parametros"
        protected String doInBackground(Object... parameters) {
            /* Translation note: Original text: "Executando doInBackground de EfetuaLogin" */
            Log.d(TAG, "Executing doInBackground of EfetuaLogin");
            TextView tLogin = (TextView) findViewById(R.id.loginText);
            TextView tSenha = (TextView) findViewById(R.id.senhaText);
            String sLogin = tLogin.getText().toString();
            String sSenha = tSenha.getText().toString();

            if (sLogin.equals("") | sSenha.equals("")) {
                /*
                  Translation notes:
                  1) "Campos Obrigatórios" -> "Required fields"
                  2) "Os campos Login e Senha são obrigatórios para autenticação do Anototudo." -> "Login and Password fields are required for Anototudo authentication."
                Alerta.popupAlertaComBotaoOK("Required fields", "Login and Password fields are required for Anototudo authentication.", LoginActivity.this);
                progressDialog.dismiss();
                return null;
            } else {
                Pattern regEx = Pattern.compile(".+@.+\\.[a-z]+");
                Matcher matcher = regEx.matcher(sLogin);
                if (!matcher.matches()) {
                    /*
                      Translation notes:
                      1) "Formato e-mail inválido" -> "Invalid email format"
                      2) "O formato do campo e-mail está inválido" -> "The email field has an invalid format"
                    */
                    Alerta.popupAlertaComBotaoOK("Invalid email format", "The email field has an invalid format",
                            LoginActivity.this);
                    progressDialog.dismiss();
                    return null;
                }
            }


            List<NameValuePair> listaParametros = new ArrayList<NameValuePair>();
            listaParametros.add(new BasicNameValuePair("login", sLogin));
            listaParametros.add(new BasicNameValuePair("senha", sSenha));
            /* Translation note: Original text: "valores recuperados dos campos de login e senha: " */
            Log.d(TAG, "values retrieved from login and password fields:" + sLogin + " | " + sSenha);

            /* Translation note: Original text: "Reutiliza cliente HttpClient disponibilizado pela Aplicação." */
            // Reuses `HttpClient` made available by the Application.
            AnototudoApp atapp = (AnototudoApp) LoginActivity.this.getApplication();
            HttpClient httpClient = atapp.getHttpClient();

            String result = null;
            try {
                result = HttpProxy.httpPost(AnototudoMetadata.URL_AUTENTICACAO, httpClient, listaParametros);
            } catch (IOException e) {
                Log.e(TAG, "IOException, Sem conectividade com o servidor do Anototudo! " + e.getMessage());
                e.printStackTrace();
                return result;
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);

            if (result == null || result.equals("")) {
                progressDialog.dismiss();
                /*
                  Translation notes:
                  1) "Dados incorretos" -> "Incorrect data"
                  2) "Os dados informados não foram encontrados no Sistema! Informe novamente ou cadastre-se antes pela internet." -> "The reported data was not found in the System! Please report again or sign up on the internet first."
                */
                Alerta.popupAlertaComBotaoOK(
                                "Incorrect data",
                                "The reported data was not found in the System! Please report again or sign up on the internet first.",
                                LoginActivity.this);
                return;
            }
            /* Translation note: Original text: "Login passou persistindo info de login local no device" */
            Log.d(TAG, "Login passed persisting local login info on device");
            ContentValues contentValues = new ContentValues();
            contentValues.put(AnototudoMetadata.LOGIN_EMAIL, sLogin);
            contentValues.put(AnototudoMetadata.LOGIN_SENHA, sSenha);
            contentValues.put(AnototudoMetadata.LOGIN_SENHA_GERADA, result);
            LoginDB loginDB = new LoginDB();
            loginDB.addLogin(LoginActivity.this, contentValues);
            /* Translation note: Original text: "Persistiu info de login no device, redirecionando para menu principal do Anototudo" */
            Log.d(TAG, "Persisting login info on device, redirecting to Anototudo main menu");
            /* Translation note: Original text: "O retorno da chamada foi ==>> " */
            Log.d(TAG, "The callback was ==>>" + result);
            /* Translation note: Original text: "tudo ok chama menu principal" */
            // everything ok call main menu
            /* Translation note: Original text: "Device foi corretametne autenticado, chamando tela do menu principal do Anototudo." */
            Log.d(TAG, "Device has been correctly authenticated by calling the main menu screen of Annotate.");

            String actionName = "br.com.anototudo.intent.action.MainMenuView";
            Intent intent = new Intent(actionName);
            LoginActivity.this.startActivity(intent);
            progressDialog.dismiss();
        }

    }

Now it works as expected but I have to say I am a bit confused as AsyncTask documentation says you could use execute to pass parameters to your task.