Reputation: 6128
i have 2 AsyncTask
, AsyncOne
and AsyncTwo
.
In First AsyncTask background method i am getting a string value and setting that in onpostexecute
.,
like this item = i.getname();
here item
is a global variable.
Now i am setting this item value is onpostexecute
method of AsyncTwo but i get null there ?
How to get the item value?
Upvotes: 0
Views: 322
Reputation: 12148
From your description it sounds you have two concurrent tasks running in the background, and task2 depends on the result of task1. Since they are running concurrently, task2 may finish before task1 does, so there's no guarantee that when task2 finishes, it will get the result of task1.
To ensure that you can run two tasks concurrently, you can synchronize the doInBackround()
method of task1, and offer a synchronized getItem()
method in task1:
// in task1
private Object item; // instance variable to be set in doInBackground
protected synchronized Object doInBackground(Object... objects) {
// set item to some value here
item = ...;
}
public synchronized Object getItem () {
return item;
}
// in task2
protected Object doInBackground(Object... objects) {
// do work of task2
....
// when finishing our work, ready to get the result of task1.
// we don't call task1.getItem() in onPostExecute() to avoid possibly blocking the UI thread
Object item = task1.getItem();
// pass item to the onPostExecute method
}
With the above code, task2 will wait for task1 to finish and get the result if it runs faster than task1.
Upvotes: 0
Reputation: 3443
what you are doing is right with your code and global variable stuff,just make sure that your both asyncTask shouldn't be in running mode simultaneously.Start second task in first's postExecute().
Upvotes: 1
Reputation: 1742
you have to make sure asynctask 1 is finished when you start async task 2. You can keep item as a field in asynctask 1, than can call publishProgress when you can set the value, and start asynctask 2 in task 1's onProgressUpdate
.
Upvotes: 0