Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to make sure an AsyncTask is terminated before I call another method?

The situation is very simple. I use an AsyncTask to retrieve a String from an HttpClient.

Now I need the String retrieved by the AsyncTask to call another method on that String,

therefore i need to make sure the AsyncTask has terminated before calling the other method.

How do I do this?

Thanks for any suggestion.

like image 998
Lisa Anne Avatar asked Jan 29 '26 19:01

Lisa Anne


2 Answers

Use a simple lock or mutex. Basically, add a variable and a getter in your AsyncTask:

public boolean locked;

public boolean isLocked(){
    return locked;
}

in your AsyncTask's onPreExecute method, add:

locked = true;

and in the onPostExecute method, add:

locked = false;

Any outside methods can then be placed into a loop such as:

MyTask foo = new MyTask();
foo.execute();
while (foo.isLocked())
{
    //wait, or sleep, or whatever
}
//here is where you execute code.
like image 81
Phil Avatar answered Feb 01 '26 13:02

Phil


Just check if onPostExecute() already was called

like image 44
amukhachov Avatar answered Feb 01 '26 14:02

amukhachov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!