Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for ASyncTask to finish or variable to be set

I am trying to set a variable in an activity to the result of my AsyncTask. I have read that I cannot return a variable and that I would have to set up the variable in my activity and then change it in the onPostExecute method.

My problem is that after the AsyncTask finishes I need to use that variable. I am having trouble with this because all the solutions I have tried so far cause the UI to freeze up and then go non-responding.

What I have tried so far:

while (!task.isCancelled()) {
    // Wait... 
}

And

while (variable == null) { 
    // Wait ...
}

Is what I am doing the best way to pass a variable from the AsyncTask to my Activity? If it is then how can I wait for the task to finish in the activity without locking up the UI?

like image 829
Dan Avatar asked Dec 26 '12 20:12

Dan


1 Answers

If you are dependent on the result of an AsyncTask, you can do this.

Object result = asyncTask.execute().get();

The type of the result is the return type in your doInBackground() method. But then your main thread will be waiting until the task is complete.

like image 146
Shiva Avatar answered Oct 04 '22 19:10

Shiva