Home > android > Show ProgressDialog on UI Thread

Show ProgressDialog on UI Thread

October 8Hits:3
Advertisement

Possible Duplicate:
Updating progress dialog in Activity from AsyncTask

I am developing my first Android App and I need a ProgressDialog to be showed while a background task, in this case just a http call on the server, happens. I did a bit of studying on this and also have already checked other threads related to this subject.

http://developer.android.com/reference/android/os/AsyncTask.html

Android show ProgressDialog until activity UI finished loading

Android SplashScreen

http://android-developers.blogspot.com/2009/05/painless-threading.html

Among others.

Than I got to write a bit of code:

1) In My Activity I declare a variable to be of type ProgressDialog

public class LoginActivity extends Activity {      public static final String TAG = "LoginActivity";      protected ProgressDialog progressDialog;  ... 

2) I have also written an inner class to extend AsyncTask as required, here in the doInBackGround is where I call a static method which actually do the POST http request to the server, in the server side I have blocked the server response 20s to validate the progress dialog.

class EfetuaLogin extends AsyncTask<Object, Void, String> {          private final static String TAG = "LoginActivity.EfetuaLogin";          @Override         protected void onPreExecute()         {             Log.d(TAG, "Executando onPreExecute de EfetuaLogin");         }           @SuppressWarnings("unchecked")         @Override         protected String doInBackground(Object... parametros) {             Log.d(TAG, "Executando doInBackground de EfetuaLogin");             Object[] params = parametros;             HttpClient httpClient = (HttpClient) params[0];             List<NameValuePair> listaParametros = (List<NameValuePair>) params[1];             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)         {             progressDialog.dismiss();         }      }  

3) When the button is pressed I than build the ProgressDialog anc call the AsyncTask I have created:

    OnClickListener loginListener = new OnClickListener() {       public void onClick(View v) {   //next line should start progress dialog in main thread ?????    progressDialog = ProgressDialog.show(LoginActivity.this, "Login in", "Wait a moment please", true, false);     //next couple of lines should do an ascyn call to server    EfetuaLogin efetuaLogin = new EfetuaLogin();    efetuaLogin.execute(params);    try {     //recover the server response and sets time out to be 25seconds     sResposta = efetuaLogin.get(25, TimeUnit.SECONDS); 

Well, this is it, I believe this was suppose to show a progress dialog while the AsyncTask would query the server in background, but what I get is NO progress bar until server response arrives and than for a fraction of time(less than 1 second) the progress shows and the next Activity is called.

As I mentioned I have re-checked this code and simply can't find where I got it wrong. Any suggestions?

Thank you in advance.

Hi, as suggested by Charlie Sheen(???) in the first answer for this thread I have tryied changing a bit of my code and now it is like(Unfortunatelly it is not working as expected so far):

OnClickListener loginListener = new OnClickListener() {         public void onClick(View v) {                 //async call????????         new EfetuaLogin().execute(params); ... 

And than do all the work to deal with response in the AsyncTask:

class EfetuaLogin extends AsyncTask<Object, Void, String> {          private final static String TAG = "LoginActivity.EfetuaLogin";          @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         protected String doInBackground(Object... parametros) {             Log.d(TAG, "Executando doInBackground de EfetuaLogin");             Object[] params = parametros;             HttpClient httpClient = (HttpClient) params[0];             List<NameValuePair> listaParametros = (List<NameValuePair>) params[1];             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();                 Alerta                         .popupAlertaComBotaoOK(                                 "Dados incorretos",                                 "Os dados informados não foram encontrados no Sistema! Informe novamente ou cadastre-se antes pela internet.",                                 LoginActivity.this);                 return;             }              Log.d(TAG, "Login passou persistindo info de login local no 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);             Log.d(TAG, "Persistiu info de login no device, redirecionando para menu principal do Anototudo");             Log.d(TAG, "O retorno da chamada foi ==>> " + result);             // tudo ok chama menu principal             Log.d(TAG, "Device foi corretametne autenticado, chamando tela do menu principal do Anototudo.");              String actionName = "br.com.anototudo.intent.action.MainMenuView";             Intent intent = new Intent(actionName);             LoginActivity.this.startActivity(intent);             progressDialog.dismiss();         }      }  

Complete OnClickListener:

OnClickListener loginListener = new OnClickListener() {     public void onClick(View v) {         Log.d(TAG, "Usuario logado, chamando menu principal");         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("")) {             Alerta.popupAlertaComBotaoOK("Campos Obrigatórios",                     "Os campos Login e Senha são obrigatórios para autenticação do Anototudo.", LoginActivity.this);             return;         } else {             Pattern regEx = Pattern.compile(".+@.+\\.[a-z]+");             Matcher matcher = regEx.matcher(sLogin);             if (!matcher.matches()) {                 Alerta.popupAlertaComBotaoOK("Formato e-mail inválido", "O formato do campo e-mail está inválido",                         LoginActivity.this);                 return;             }         }           List<NameValuePair> listaParametros = new ArrayList<NameValuePair>();         listaParametros.add(new BasicNameValuePair("login", sLogin));         listaParametros.add(new BasicNameValuePair("senha", sSenha));          Log.d(TAG, "valores recuperados dos campos de login e senha: " + sLogin + " | " + sSenha);          // Reutiliza cliente HttpClient disponibilizado pela Aplicação.         AnototudoApp atapp = (AnototudoApp) LoginActivity.this.getApplication();         HttpClient httpClient = atapp.getHttpClient();          //prepara lista de parametros para fazer chamada asíncrona no servidor para autenticar.         Object[] params = new Object[2];         params[0] = httpClient;         params[1] = listaParametros;          //faz chamada assincrona         new EfetuaLogin().execute(params);     } }; 

Answers

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) {
            Log.d(TAG, "Executando OnclickListener");

            //faz chamada assincrona
            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
        protected String doInBackground(Object... parametros) {
            Log.d(TAG, "Executando doInBackground de 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("")) {
                Alerta.popupAlertaComBotaoOK("Campos Obrigatórios",
                        "Os campos Login e Senha são obrigatórios para autenticação do Anototudo.", LoginActivity.this);
                progressDialog.dismiss();
                return null;
            } else {
                Pattern regEx = Pattern.compile(".+@.+\\.[a-z]+");
                Matcher matcher = regEx.matcher(sLogin);
                if (!matcher.matches()) {
                    Alerta.popupAlertaComBotaoOK("Formato e-mail inválido", "O formato do campo e-mail está inválido",
                            LoginActivity.this);
                    progressDialog.dismiss();
                    return null;
                }
            }

            List<NameValuePair> listaParametros = new ArrayList<NameValuePair>();
            listaParametros.add(new BasicNameValuePair("login", sLogin));
            listaParametros.add(new BasicNameValuePair("senha", sSenha));

            Log.d(TAG, "valores recuperados dos campos de login e senha: " + sLogin + " | " + sSenha);

            // Reutiliza cliente HttpClient disponibilizado pela Aplicação.
            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();
                Alerta
                        .popupAlertaComBotaoOK(
                                "Dados incorretos",
                                "Os dados informados não foram encontrados no Sistema! Informe novamente ou cadastre-se antes pela internet.",
                                LoginActivity.this);
                return;
            }

            Log.d(TAG, "Login passou persistindo info de login local no 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);
            Log.d(TAG, "Persistiu info de login no device, redirecionando para menu principal do Anototudo");
            Log.d(TAG, "O retorno da chamada foi ==>> " + result);
            // tudo ok chama menu principal
            Log.d(TAG, "Device foi corretametne autenticado, chamando tela do menu principal do Anototudo.");

            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.

Thank you.

Related Articles

  • Show ProgressDialog on UI Thread October 8

    Possible Duplicate: Updating progress dialog in Activity from AsyncTask I am developing my first Android App and I need a ProgressDialog to be showed while a background task, in this case just a http call on the server, happens. I did a bit of studyi

  • Show a ProgressDialog and send an SMS in the backgroundSeptember 27

    I have written a procedure that shows a ProgressDialog sends an SMS updates the View from another thread hides the ProgressDialog But it seems to me that this is not the best way to do this. I would like to hear advice and my mistakes. It seems to me

  • ViewPager Fragment not showing ProgressDialogJanuary 21

    I have a tabbed activity that uses a ViewPager to navigate through three fragments. when I load a fragment I have to load some data so I put the loading code inside an AsyncTask and I wanted to show a ProgressDialog while the data is being loaded. Th

  • How to show progress Bar when the thread is waitingJanuary 22

    dialog = new ProgressDialog(activity); dialog.show(); synchronized (this) { Log.d(LOG_TAG, "Waiting for closed rides to be loaded"); try { wait(); } catch (InterruptedException e) { } } } dialog.dismiss(); I have tried using above code for progr

  • in signin the method gettext must be called from ui thread errorJanuary 26

    I'm trying to create a login for an application. However I have a problem. This is my code: in this code there is an error in the getText() in the android studio actually m creating a login page with the help of the JSONParsing of web API, the login

  • Showing a progressDialog from an OptionsMenuJanuary 26

    I know the following is probably not the best practice and not recommended to do. I have an AsyncTask that sends data to server. The whole process that i need to do includes 4 web calls using this AsyncTask in quick succession. I understand that with

  • Android app not giving a response of GET request in a new ThreadJanuary 26

    Please help, as the code below that should send a GET request does not work. Behaviour: after tapping the button it writes "Running", then uses some traffic, then after some time hangs and crashes. My goal is to send HTTP GET and handle the resp

  • Android okhttp Async progressdialogFebruary 7

    I want to add progressdialog into okhttp (asynchronous, not AsyncTask) but i got this error: Error: Can't create handler inside thread that has not called Looper.prepare() How to fix it in a proper way? I want to be sure that is the best way to do th

  • Getting issue of suspending threads while running multiple AsyncTasks

    Getting issue of suspending threads while running multiple AsyncTasksFebruary 15

    I have a layout of nested Tabs with ViewPager in one Fragment of an application which looks like . Each Fragment of nested fragments is showing data into ListView using WebServices. public class IndicesFragment extends android.support.v4.app.Fragment

  • how to solve this error Exception in thread "main" java.lang.NullPointerException? October 20

    What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely? --------------Solutions---

  • NullPointerException thrown with java.lang.Thread.run(Unknown Source) October 20

    What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely? --------------Solutions---

  • Exception in thread "Main" java.lang.NullPointerException LWJGL 3 October 20

    What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely? --------------Solutions---

  • Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException, when using AWT and Swing October 20

    What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely? --------------Solutions---

  • Strange behavior of loop index and thread in C# November 7

    I met an interesting issue about C#. I have code like below. List<Func<int>> actions = new List<Func<int>>(); int variable = 0; while (variable < 5) { actions.Add(() => variable * 2); ++ variable; } foreach (var act in action

  • What is the difference between "Thread.CurrentThread.CurrentUICulture.DateTimeFormat" and "Thread.CurrentThread.CurrentCulture.DateTimeFormat"? November 30

    In .NET there is the CultureInfo class in the System.Globalization namespace. It has two similar properties both returning values of the CultureInfo type: CurrentCulture and CurrentUICulture. What is the difference between them? Which one should I us

  • Runnable vs. "extends Thread"

    Runnable vs. "extends Thread" February 12

    From what time I've spent with threads in Java, I've found these two ways to write threads: With implements Runnable: public class MyRunnable implements Runnable { public void run() { //Code } } //Started with a "new Thread(new MyRunnable()).start()&

  • What is the difference between a thread and a fiber?April 28

    What is the difference between a thread and a fiber? I've heard of fibers from ruby and I've read heard they're available in other languages, could somebody explain to me in simple terms what is the difference between a thread and a fiber. ----------

  • Can Windows be configured to only use a single hardware thread?

    Can Windows be configured to only use a single hardware thread?May 27

    Is is possible to configure Windows to only use a single hardware-thread. Every machine for the last couple of years seems to be at least dual-core, but some timing bugs are only reproducible when threads execute serially. I am particularly intereste

  • When to change SQL 2005 max worker threads on 64-bit serverJune 29

    Server Environment: Windows 2003 Standard R2 x64 SP2 SQL 2005 Enterprise 64-bit SP2 HP ProLiant BL460c G1, Xeon E5440 2.83 Ghz processors (Quad-core) 8 GB RAM EDIT: I should also note that max_workers_count is currently at the default 512 for a 4 pro

  • Max # of threads per CPUJuly 6

    I'm currently using Visual Studio Test Suite load tester to simulate a load against on of our web apps on a different server. (No, I'm not testing against production). I believe it is creating a thread per simulated user. While I was doing this, I ex

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 2.246 s.