I'm trying to start an AsyncTask from another AsyncTask's doInBackground()
-method...
Is this even possible? If yes, how can I achieve this?
LATER EDIT:
The idea is that I start an asynctask that will get me statuses from Tweeter ... Everything ok until here ... But when I encounter some specific tweets I need to modify them with some info from my server, here I will make another network operation, and since I need to wait until I get the info from my server I do:
GetContent getContentServiceAsyncTask = new GetContent(context);
try {
tweetText = Uri.decode(getContentServiceAsyncTask.execute(
URL_GET_CONTENT, jsonRequest).get());
} catch (InterruptedException e) {
Log.e(TAG_DEBUG, "InterruptedException: ", e);
} catch (ExecutionException e) {
Log.e(TAG_DEBUG, "ExecutionException: ", e);
}
This is started from the allready started AsyncTask in doInBackground() method ...
I know I can just add the methods in the AsyncTask and just call them in the doInBackground() method, but I need to use them in other places, where I start these AsyncTasks from onPostExecute ...
If you guys think there is an easy work-around for this, that won't affect my performance, that will be great ... if not I will make some static methods that I will call in all the AsyncTasks I need(but this will require me to modify a lot of my code)
According to the post below you can do Activity.runOnUiThread() to run a Runnable on the main-Thread (from another thread).
So theoretically you could do this:
As the name says Activity.runOnUiThread() executes the runnable on the main-thread
But it's kind of hacky.
Code should look something like this: (didnt test)
// first task
(new AsyncTask<String, String, String>() {
@Override
protected String doInBackground(String... params) {
ParentActitity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//second async stared within a asynctask but on the main thread
(new AsyncTask<String, String, String>() {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}).execute();
}
});
return null;
}
}).execute();
This nested example is not a good style to use in production because (IMHO) its close to unreadable.
Additional Notes:
Activity.runOnUiThread(Runnable) is not static! Thats why my example uses ParentActivity(.this).runOnUiThread(Runnable).
AsyncTasks
are supposed to run from main (UI) thread. You should not run another AsyncTask from doInBackground because this method is executed on a non-UI thread.
In your case, I can suggest you two things:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With