0

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?

4

3 回答 3

1

你所做的对你的代码和全局变量的东西是正确的,只要确保你的两个 asyncTask 不应该同时处于运行模式。在第一个 postExecute() 中启动第二个任务。

于 2013-02-02T07:17:45.090 回答
0

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.

于 2013-02-02T07:14:56.783 回答
0

根据您的描述,听起来您有两个并发任务在后台运行,并且task2取决于task1的结果。由于它们同时运行,因此task2可能在task1之前完成,因此不能保证当task2完成时,它会得到task1的结果。

为确保可以同时运行两个任务,可以同步 task1 的方法doInBackround(),并在task1中提供同步方法:getItem()

// 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
}

使用上面的代码,task2将等待task1完成并获得结果,如果它运行得比task1快。

于 2013-02-02T07:26:18.370 回答