Issue
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)
Solution
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:
- Run the Async Task
- do Activity.runOnUiThread(Runnable) inside your AsyncTask and start a new AsyncTask from inside of this runnable
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).
Answered By - Langusten Gustel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.