How to return global variable within a Requesttask class

Asked

Viewed 736 times

1

Well I use the Requesttask class to do some things like:

  • protected string doInBackground(String... Uri)
  • protected void onPostExecute(String result)

so I want to return the variables to do other things outside the Requesttask class, I read something about variable scope but I don’t know how to do.

Ex.:

public class Inicio_Activity ...{

// minha classe requesttask..
class RequestTask extends AsyncTask<String, String, String>{

...meus comandos...

teste = "Pronto";

}

// declaro a string
String teste = "";

// Oncreate
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

new RequestTask().execute(http://www.asdasdas.com);

// digamos que tenho um textview que ira receber essa variável onde deveria aparecer "Pronto", como minha classe não retorna essa variável, não ira exibir nada.
texto1.setText(teste);

}
  • See, when using Asynctask you are saying that something should run in a separate Thread and that you do not know when it will be finished. Since you expect a return and your Asynctask class is within Activity, create a static variable that can be used between classes. Keep in mind that you will never know when the test variable was set, because you don’t know when the Thread will be finished!

  • ok put Static, in case I call the variable after calling the class Asynctask, is not returning me anything, as you said that this is hardly known when will have "result", as I will do for when she has, that displays this result?

  • Obs: I tested it here and it’s working but like you said. open the app: shows nothing. close and open dnv: correctly displays the variable.

  • got it now, it does not display pq when I called it, the Asynctask class had not worked, then when I open it again it is called and appears, because the class already has the result, now I just have to see how I wait for it to have the result to proceed.

  • Just migrate the texto1.setText(...) for the end of the method onPostExecute. Ensures you already have the result and are updating the View in Main Thread.

  • I already have some commands inside onPostExecute, but my idea was to take this variable inside onCreate to be used in a Broadcastreceiver (displayed in a notification). Static has already helped more in any way, when Broadcastreceiver is searching this variable will have to find something..

  • The Asynctask class has a final get method, I’m not sure, but it seems to return the result after completing the task. It will look like this: RequestTask rt = new RequestTask(); rt.execute(http://www.asdasdas.com); String retorno = rt.get(); Remembering that I did not test. I took for official documentation!

Show 2 more comments

2 answers

1

You are in front of a major problem of Android: the concept of Async. Unlike iOS that authorizes block the user, Android, with the Async system, does not allow. Even if you use a global variable in Async, it will change little because Async works in a way.... Async! It means that nothing can demonstrate that when you want to use the global variable, it will get the result you are waiting for.

Has 2 options:

1) create a "Callback" and make the entire treatment within the Async

2) Force Async to wait (option not well in Android spirit!!)

Example of Callback with an HTTP Request:

public Biblio_HTTP(OnHttpTaskCompleted listener)
{
    super();
    this.listener = listener;
}

@Override
protected void onPreExecute()
{
    super.onPreExecute();
}

@Override
protected String doInBackground(String... url) {
    String text =null;
   <CUT>
}

@Override
protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);

}


@Override
protected void onPostExecute(String result) {
    listener.OnHttpTaskCompleted(result);    // Callback
}

// Def do Callback
public interface OnHttpTaskCompleted {

    void OnHttpTaskCompleted(String result);
}
}

  public class Callback implements Biblio_HTTP. OnHttpTaskCompleted {
    @Override

    public void OnHttpTaskCompleted(String result) {

        // Aqui vc faz o que vc quer com o resultado
    }
}

Example 2 with a blocked Alert":

    AlertDialog alert = builder.create();
    alert.show();
    try { Looper.loop(); }
    catch(RuntimeException e2) {}

    return resultado_alert;

0

In the Requesttask constructor you pass the Textview text1 parameter, and in the onPostExecute() method, put the text1.setText command line ("your text").

Example:

public RequestTask(TextView texto) {
        this.texto = texto;
    }

@Override
    protected void onPostExecute() {
        texto1.setText("seu texto");
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.