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!
– Ascension
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?
– JBarbosa
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.
– JBarbosa
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.
– JBarbosa
Just migrate the
texto1.setText(...)
for the end of the methodonPostExecute
. Ensures you already have the result and are updating theView
inMain Thread
.– Wakim
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..
– JBarbosa
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!– Ascension