AsyncTask、HttpClient 和 ProgressDialog

发布于 2024-12-29 18:35:39 字数 4511 浏览 2 评论 0原文

我正在创建一个 AsyncTask 来将用户登录到服务器。 登录工作正常,但 ProgressDialog 直到进程结束才显示。 一旦用户点击按钮,用户界面就会冻结,并且我的对话框不会显示。

我很感激任何帮助。这是我的代码。

public class MyApp extends Activity {
    private ProgressDialog dialogo = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button loginButton = (Button) findViewById(R.id.btnLogin);
        loginButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                SharedPreferences preferencias = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                String webAddress = preferencias.getString("webAddress", "");

                if (webAddress.isEmpty()) {
                    Toast.makeText(getBaseContext(), "Please, configure a Web Address.", Toast.LENGTH_LONG).show();
                } else {
                    EditText edtUsername = (EditText) findViewById(R.id.edtUsername);
                    EditText edtPassword = (EditText) findViewById(R.id.edtPassword);

                    HashMap<String, String> parametros = new HashMap<String, String>();
                    parametros.put("username", edtUsername.getText().toString());
                    parametros.put("password", edtPassword.getText().toString());

                    Requisicao requisicao = new Requisicao(parametros);
                    AsyncTask<String, Void, String> resposta = requisicao.execute(webAddress + "/login");

                    try {
                        Toast.makeText(getBaseContext(), resposta.get(), Toast.LENGTH_LONG).show();
                    } catch (InterruptedException e) {
                        Toast.makeText(getBaseContext(), "InterruptedException (login)", Toast.LENGTH_LONG).show();
                    } catch (ExecutionException e) {
                        Toast.makeText(getBaseContext(), "ExecutionException (login)", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });

        ImageView engrenagem = (ImageView) findViewById(R.id.imgEngrenagem);
        engrenagem.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent preferenciasActivity = new Intent(getBaseContext(), Preferencias.class);
                startActivity(preferenciasActivity);
            }
        });
    }



    public class Requisicao extends AsyncTask<String, Void, String> {
        private final HttpClient clienteHttp = new DefaultHttpClient();
        private String resposta;
        private HashMap<String, String> parametros = null;

        public Requisicao(HashMap<String, String> params) {
            parametros = params;
        }

        @Override
        protected void onPreExecute() {
            dialogo = new ProgressDialog(MyApp.this);
            dialogo.setMessage("Aguarde...");
            dialogo.setTitle("Comunicando com o servidor");
            dialogo.setIndeterminate(true);
            dialogo.setCancelable(false);
            dialogo.show();
        }

        @Override
        protected String doInBackground(String... urls) {
            byte[] resultado = null;
                HttpPost post = new HttpPost(urls[0]);
            try {
                ArrayList<NameValuePair> paresNomeValor = new ArrayList<NameValuePair>();
                Iterator<String> iterator = parametros.keySet().iterator();
                while (iterator.hasNext()) {
                    String chave = iterator.next();
                    paresNomeValor.add(new BasicNameValuePair(chave, parametros.get(chave)));
                }

                post.setEntity(new UrlEncodedFormEntity(paresNomeValor, "UTF-8"));

                HttpResponse respostaRequisicao = clienteHttp.execute(post);
                StatusLine statusRequisicao = respostaRequisicao.getStatusLine();
                if (statusRequisicao.getStatusCode() == HttpURLConnection.HTTP_OK) {
                    resultado = EntityUtils.toByteArray(respostaRequisicao.getEntity());
                    resposta = new String(resultado, "UTF-8");
                }
            } catch (UnsupportedEncodingException e) {
            } catch (Exception e) {
            }
            return resposta;
        }

        @Override
        protected void onPostExecute(String param) {
            dialogo.dismiss();
        }
    }
}

I'm creating a AsyncTask to login user to a server.
The login works fine, but the ProgressDialog does not show until the end of the process.
As soon as the user taps the button, the UI freezes, and my dialog does not show up.

I appreciate any help. Here's my code.

public class MyApp extends Activity {
    private ProgressDialog dialogo = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button loginButton = (Button) findViewById(R.id.btnLogin);
        loginButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                SharedPreferences preferencias = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                String webAddress = preferencias.getString("webAddress", "");

                if (webAddress.isEmpty()) {
                    Toast.makeText(getBaseContext(), "Please, configure a Web Address.", Toast.LENGTH_LONG).show();
                } else {
                    EditText edtUsername = (EditText) findViewById(R.id.edtUsername);
                    EditText edtPassword = (EditText) findViewById(R.id.edtPassword);

                    HashMap<String, String> parametros = new HashMap<String, String>();
                    parametros.put("username", edtUsername.getText().toString());
                    parametros.put("password", edtPassword.getText().toString());

                    Requisicao requisicao = new Requisicao(parametros);
                    AsyncTask<String, Void, String> resposta = requisicao.execute(webAddress + "/login");

                    try {
                        Toast.makeText(getBaseContext(), resposta.get(), Toast.LENGTH_LONG).show();
                    } catch (InterruptedException e) {
                        Toast.makeText(getBaseContext(), "InterruptedException (login)", Toast.LENGTH_LONG).show();
                    } catch (ExecutionException e) {
                        Toast.makeText(getBaseContext(), "ExecutionException (login)", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });

        ImageView engrenagem = (ImageView) findViewById(R.id.imgEngrenagem);
        engrenagem.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent preferenciasActivity = new Intent(getBaseContext(), Preferencias.class);
                startActivity(preferenciasActivity);
            }
        });
    }



    public class Requisicao extends AsyncTask<String, Void, String> {
        private final HttpClient clienteHttp = new DefaultHttpClient();
        private String resposta;
        private HashMap<String, String> parametros = null;

        public Requisicao(HashMap<String, String> params) {
            parametros = params;
        }

        @Override
        protected void onPreExecute() {
            dialogo = new ProgressDialog(MyApp.this);
            dialogo.setMessage("Aguarde...");
            dialogo.setTitle("Comunicando com o servidor");
            dialogo.setIndeterminate(true);
            dialogo.setCancelable(false);
            dialogo.show();
        }

        @Override
        protected String doInBackground(String... urls) {
            byte[] resultado = null;
                HttpPost post = new HttpPost(urls[0]);
            try {
                ArrayList<NameValuePair> paresNomeValor = new ArrayList<NameValuePair>();
                Iterator<String> iterator = parametros.keySet().iterator();
                while (iterator.hasNext()) {
                    String chave = iterator.next();
                    paresNomeValor.add(new BasicNameValuePair(chave, parametros.get(chave)));
                }

                post.setEntity(new UrlEncodedFormEntity(paresNomeValor, "UTF-8"));

                HttpResponse respostaRequisicao = clienteHttp.execute(post);
                StatusLine statusRequisicao = respostaRequisicao.getStatusLine();
                if (statusRequisicao.getStatusCode() == HttpURLConnection.HTTP_OK) {
                    resultado = EntityUtils.toByteArray(respostaRequisicao.getEntity());
                    resposta = new String(resultado, "UTF-8");
                }
            } catch (UnsupportedEncodingException e) {
            } catch (Exception e) {
            }
            return resposta;
        }

        @Override
        protected void onPostExecute(String param) {
            dialogo.dismiss();
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

画中仙 2025-01-05 18:35:39

尝试注释掉按钮侦听器中的 resposta.get() 调用。我猜它只是阻塞主 UI 线程,直到任务完成。

Try to comment out resposta.get() call in the button listener. I guess it just blocks the main UI thread untill the task is finished.

把回忆走一遍 2025-01-05 18:35:39

夫妇的事情。首先,不要为 ASyncClass 创建实例,因为根据 android 文档,您只能调用它一次。因此,像这样执行: new Requisicao().execute(webAddress + "/login");

另外,不要调用 requisicao.get(),这将再次根据根据文档“如果需要,则等待计算完成,然后检索其结果”(也称为阻塞),从异步类中添加一个覆盖:

protected void onProgressUpdate(Long... progress) {
    CallBack(progress[0]); // for example
}

其中 CallBack 是 UI 线程中的一个函数,它将长期处理您的进度, 或者字符串,或者任何你想扔回去的东西。请注意,您的 ASync 类必须在 UI 类中定义,而不是单独定义。

Couple things. First of all, don't make an instance for ASyncClass because you can only ever call it once, as per the android documentation. So execute like this: new Requisicao().execute(webAddress + "/login");

Also, instead of calling requisicao.get(), which will, again according to documentation "Waits if necessary for the computation to complete, and then retrieves its result" (also known as blocking), from within your async class add an override:

protected void onProgressUpdate(Long... progress) {
    CallBack(progress[0]); // for example
}

Where CallBack is a function in your UI thread which will handle processing your progress long, or string, or whatever else you want to throw back. Mind you, your ASync class will have to be defined within the UI class instead of separately.

黑白记忆 2025-01-05 18:35:39

将您的内容

  private ProgressDialog dialogo = null;

移至 AsyncTask 的字段中,就像使用 HTTPClient 一样,因为您不这样做
似乎在任何地方都可以使用它
构造函数中创建对话框

public Requisicao(HashMap<String, String> params) {
            parametros = params;
          dialogo = new ProgressDialog(MyApp.this);
        }

尝试在postExecute 的

 if (dialogo .isShowing()) {
                dialogo .dismiss();
 }

希望它有帮助。

move your

  private ProgressDialog dialogo = null;

into the AsyncTask's fields as you did it with HTTPClient because you don't
seem to use it anywhere and
try to create your dialog in the constructor

public Requisicao(HashMap<String, String> params) {
            parametros = params;
          dialogo = new ProgressDialog(MyApp.this);
        }

in postExecute

 if (dialogo .isShowing()) {
                dialogo .dismiss();
 }

hope it helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文