Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Using AsyncTask

Hi all, I' ve been playing around with the blog reader and I've got a question about the AsyncTask - hopefully an easily answered one :).

I've scanned through the documentation and it says 'execute' should only be called once, otherwise an exception will be thrown. So if I wanted implement some sort of refresh method that checks for new posts at say the touch of a button, how would I get the code in 'doInBackgroud' to run again without calling it directly?

2 Answers

Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

Each instance can only be run once, but you can create a new instance to run another task. I wrote the BlogReader one as two lines for clarity, but check out this example of executing it from a new instance every time

Hi Ben, thanks for the response!

After pondering for on it for a bit I ended up doing exactly that! I also added a boolean flag too that gets set to true just before the execute is called, to signify if the previous thread is busy (true). Then in onPostExecute() I can set the flag to false showing the task had completed.

That way I can stop users from overloading on the Http requests (and using up my api requests)