2012-01-27 8 views
2

사용자를 서버에 로그인하도록 AsyncTask를 만듭니다. 로그인은 정상적으로 작동하지만 ProgressDialog는 프로세스가 끝날 때까지 표시되지 않습니다. 사용자가 버튼을 탭하자 마자 UI가 멈추고 대화 상자가 표시되지 않습니다.AsyncTask, HttpClient 및 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(); 
     } 
    } 
} 

답변

4

버튼 리스너에서 resposta.get()으로 전화를 걸어보세요. 나는 그것이 작업이 끝날 때까지 메인 UI 스레드를 차단한다고 생각한다.

+0

@Felsangom : 도움이된다면 onPostExecute()에서 작업 결과 처리를 이동하십시오. –

+0

그것은 작동합니다. 감사! – Felsangom

1
당신이 HttpClient를 함께했던 것처럼 어디서든 사용할 것 같지 않기 때문에 AsyncTask를의 필드에 당신의

private ProgressDialog dialogo = null; 

이동

와 생성자에서 대화 상자를 만들려고

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

도움이 되길 바랍니다.

+0

아니요. UI가 여전히 고정되어 있습니다. – Felsangom

+0

어떤 버튼을 탭 했습니까? 동결 한 후에? –

2

몇 가지. 먼저, ASyncClass에 대한 인스턴스를 만들지 마십시오. 왜냐하면 안드로이드 문서에 따라 한 번만 호출 할 수 있기 때문입니다. 따라서 다음과 같이 실행하십시오. new Requisicao().execute(webAddress + "/login");

requisicao.get()을 호출하는 대신, "계산이 완료 될 때까지 대기 한 다음 그 결과를 검색합니다"(차단이라고도 함) 설명서를 다시 읽습니다. 비동기 클래스는 재정의를 추가

콜백이 다시 던져 원하는 어떤 다른 진행 긴 처리, 또는 문자열, 또는 처리됩니다 UI 스레드에서 함수입니다
protected void onProgressUpdate(Long... progress) { 
    CallBack(progress[0]); // for example 
} 

. ASync 클래스는 별도로 UI 클래스 내에서 정의해야합니다.

+0

팁 주셔서 감사합니다. – Felsangom