我有一个简单的异步任务,如下面的代码片段
protected class DownloadArticlesAsyncTask extends AsyncTask<Category, Integer, HashMap<String, Object>>
{
..
@Override
protected HashMap<String, Object> doInBackground(Category... categories)
{
HashMap<String, Object> result = new HashMap<String, Object>();
List<Article> articles = Util.getArticlesFromServer(categories);
result.put("articles", articles);
Log.d(TAG, "size = " + articles.size()); // Return 1
return result;
}
@Override
protected void onPostExecute(HashMap<String, Object> result)
{
ArrayList<Article> articles = (ArrayList<Article>) result.get("articles");
Log.d(TAG, "size = " + articles.size()); // Return 0, why?
}
}
为什么转移到onPostExecute
会返回空白,而只会在有时发生,而不是总是。
有什么想法吗?
答案 0 :(得分:0)
尝试在方法doInBackground之外声明List<Articles> articles;
...
并将List<Article> articles = Util.getArticlesFromServer(categories);
更改为articles = Util.getArticlesFromServer(categories);
它返回零,因为List中的数据保存未声明为全局。