How to get the return of the method ofInBackground in android?

0

I'm starting to work with AsyncTasks and I still do not know much. I created a class that extends AsyncTask and implemented the doInBackground() method, but my question now is how do I get the return of this method? In another class in the efetuarLogin() method, I make a call to the execute() method, but it does not return me the String that should return. How can I get the method return from the InBackground? Thank you in advance for your cooperation!

protected String doInBackground(String... params) {

    String resposta = "";

    try {
        resposta = this.sendGet(params[0]);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return resposta;
}

Method that calls the class that extends AsyncTask:

public Usuario efetuarLogin(String email, String senha){

    JSONStringer js = new JSONStringer();
    ConexaoHttp conexao = new ConexaoHttp();

    try {
        js.object();
        js.key("email").value(email);
        js.key("senha").value(senha);
        js.endObject();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    String usuario = conexao.execute(js.toString()); // não retorna uma String, dá erro dizendo que ele retorna um objeto do tipo AsyncTask

    return null;
}
    
asked by anonymous 15.07.2017 / 00:51

2 answers

1

If you're still experiencing this problem, a suggestion I've been using for some time is to use the get() method of the object instantiated with the class that inherits from AsyncTask shortly after invoking the execute() method. I confess that I can not tell if it is the most appropriate way, but I believe that for the moment, it can solve your problem. That way your code would look like this:

public Usuario efetuarLogin(String email, String senha){

    JSONStringer js = new JSONStringer();
    ConexaoHttp conexao = new ConexaoHttp();

    try {
        js.object();
        js.key("email").value(email);
        js.key("senha").value(senha);
        js.endObject();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    conexao.execute(js.toString());
    String retorno = conexao.get(); // esse método retorna a resposta do método doInBackground()

    return retorno;
}
    
23.10.2017 / 05:03
2

The doInBackground method passes the result to another AsyncTask method, onPostExecute .

In your case, if Asynctask is created in the Activity itself, you could assign the value of usuario to it:

void onPostExecute(String result) {
     usuario = result;
 }

The execute method itself does not return anything. The ideal thing is to put the rest of the code that you will use with this user also in the above method because Asynctask runs in Background and the main thread only knows that it has terminated by this method.

More details on Asynctask, you can see here:

link

    
15.07.2017 / 01:07