I have a class that extends AsyncTask.
In the doInBackground() method, I connect to a server and get data.
The said class has a method get() that returns this data to the user.
So I call execute() method in this class and soon after, return a member variable “response”.
But null is being returned because, the connection is not made yet.
So, I set the variable “response” in onPostExecute() and want to return to the main thread from here.
How will I do this without using a loop like this:
while(! gotResponse) continue;
My pseudo code:
//Main thread
class blah {
.... onCreate(..) {
ConHelper ch = new ConHelper();
String data = ch.get();
}
}
class ConHelper extends AsyncTask<...>{
private String response;
private boolean gotResponse;
... get() {
this.execute(...);
while(! this.gotResponse) continue;
return this.response;
}
... doInBackground(..) {
// connect and get data.
}
... on postExecute(...) {
//set response and gotResponse from obtained data.
}
The concept of
AsyncTaskis that the task itself initiates whatever needs to be done once the results are available. A method likeget()cannot be implemented. Certainly do not try waiting on the main (UI) thread until the results are available. (By the way,AsyncTaskalready defines aget()method to retrieve the results. If the results are not available, it will block until they are. Do not call it from the UI thread.)The way to do this is to have
onPostExecute()initiate whatever needs to be done once the results are available. This method is called on the UI thread after all the time-consuming work ofdoInBackground()has finished.Write your UI logic (
onCreate(), etc.) so that it does not have to wait on the results, and so that it works when results are not yet available. (So, for instance, you could display a blank field or a “please wait” message where you would like to displaydata. Or you could pop up a “working” alert dialog and remove it from withinonPostExecute().)