How to make connections to a php work in the background on Android

1

I have a small chat that logs in and sends messages to the server through php + JSON , but every query will crash the app for a couple of seconds, which is really annoying.

I heard something called Backgroundworker , but I do not know exactly how this works.

This is my code:

    EditText campoLogin = (EditText)findViewById(R.id.campo_de_login);
    EditText campoSenha = (EditText)findViewById(R.id.campo_de_senha);
    Conectar Conn = new Conectar("http://meusite.com/chat/login.php?login=" + campoLogin.getText() + "&senha=" + campoSenha.getText() );

    JSONArray array = new JSONArray(Conn.response);
    JSONObject object = array.getJSONObject(0);
    id = (String) object.get("id");
    nome = (String) object.get("nome");

Need to make this process not crash, and work in the background ...

    
asked by anonymous 20.05.2014 / 21:20

1 answer

1

You can create a subclass of the class AsyncTask .

private class LoginAsync extends AsyncTask<String, Integer, Boolean> {
    protected String doInBackground(String... parametros) {
       String campoLogin = parametros[0];
       String campoSenha = parametros[1];
       Conectar Conn = new Conectar("http://meusite.com/chat/login.php?login=" + campoLogin + "&senha=" + campoSenha );

       JSONArray array = new JSONArray(Conn.response);
       JSONObject object = array.getJSONObject(0);
       id = (String) object.get("id");
       nome = (String) object.get("nome");
       return nome != null;
 }

   protected void onProgressUpdate(Integer... progresso) {
       // Mostre uma barra de carregamento de acordo com o progresso.
   }

   protected void onPostExecute(Boolean login) {
       showDialog("Login com sucesso: " + login);
   }
}
    
20.05.2014 / 21:58