Ogu*_*han 5 java android android-asynctask
List完成后我有6种不同类型的结果AsyncTask.并且List结果应该返回到Activity.例如:List<A>,List<B>,List<C>,List<D>,List<E>和最后List<F>.
这是我的AsyncTask:
public class myAsync extends AsyncTask<String, String, List> {
private List resultList;
@Override
protected List doInBackground(String... params) {
//params[0] is url
//params[1] is type
callAPI api = new callAPI(params[0], params[1]);
// According to type api decides type of List and generates
return api.getJSON(); // returns a List which already parse JSON
}
@Override
protected void onPostExecute(List result) {
// Result is here now, may be 6 different List type.
this.resultList = result
}
// returns result
public List getResultList() { return this.resultList; }
}
Run Code Online (Sandbox Code Playgroud)
我会像这样调用AsyncTask:
myAsync task = new myAsync();
task.execute(params);
List myList = task.getResultList(); // type is uncertain
Log.d("Tag", Integer.toString(myList.size());
Run Code Online (Sandbox Code Playgroud)
你知道,我必须指出<>标签之间的返回类型(Result).如果我选择特定类型List,则不适用于其他类型.
实际上,我已经尝试过返回List<Object>,只有List类型.但是没有用.
我不想用6种不同的Async.是否有可能只用一个解决这个问题AsyncTask?我想我需要匿名列表或类似的东西不确定.有谁能解释一下?
首先,我应该指出,您获取列表的顺序是不正确的.让我来证明:
// Initialize myAsync
myAsync task = new myAsync();
// This will do work for some period of time, this statement DOES NOT 'block'
// till myAsync completes, it will run it in the background
task.execute(params);
// This will return null because by the time you get here, task.execute most
// likely hasn't finished yet.
task.getResultList();
Run Code Online (Sandbox Code Playgroud)
编辑:现在您已经包含了要对列表结果执行的操作,以下是修改onPostExecute方法的方法:
@Override
protected void onPostExecute(List result) {
Log.d(TAG, "The returned list contains " +result.size()+ "elements");
// Do anything else you need to with the returned list here
}
Run Code Online (Sandbox Code Playgroud)
总而言之,如果您需要对返回的列表执行任何其他操作(除了打印它们的大小),例如比较,打印项目等,您需要在onPostExecute方法中执行此操作.
| 归档时间: |
|
| 查看次数: |
4873 次 |
| 最近记录: |