【发布时间】:2015-05-11 07:42:10
【问题描述】:
这是我第一次遇到 AsyncTask onPostExecute() 的问题。我有其他 AsyncTask 在 Fragment 中工作。对于这个特定的片段类,AsyncTask doInBackground() 完成了它的执行,但 onPostExecute() 没有被调用。我尝试从 doInBackground 返回数据以及分配给 AsyncTask 中的 全局变量。但是对于这两种情况,onPostExecute 都没有调用。
这是我的代码 sn-p。
private void downloadFeedsAndTweets() {
new DownloadTwitterAsyncTask().execute("ScreenName"); // ScreenName is the proper screen name.
new DownloadInstagramFeedAsyncTask().execute("Instagram_URL"); //Instagram_URL is the actual url.
}
public class DownloadInstagramFeedAsyncTask extends AsyncTask<String, Void, Void> {
List<InstagramData> instagramFeeds = null;
@Override
protected Void doInBackground(String... params) {
try {
// calls http request to get the feeds
instagramFeeds = instagramFeedParser(JsonObject);
Log.d(TAG, "DownloadInstagramFeedAsyncTask instagramFeeds received");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// show the feeds in ui using the variable instagramFeeds if != null.
}
private List<InstagramData> instagramFeedParser(JSONObject object) throws JSONException, IOException {
// parse the json and returns the list
return instagarmFeedList;
}
}
public class DownloadTwitterAsyncTask extends AsyncTask<String, Void, Void> {
List<TwitterTweet> twitterTweets = null;
@Override
protected Void doInBackground(String... params) {
if (params.length > 0) {
// retrieves twitter tweets and assigns to variable twitterTweets.
twitterTweets = twitterAPI.getTwitterTweets(params[0]);
Log.e(TAG, "DownloadTwitterAsyncTask tweet received");
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// update ui with the twitter tweets using variable twitterTweets if != null.
}
}
相同的代码如果从活动调用有效。在片段中,两个异步任务都没有调用 onPostExecute。
【问题讨论】:
-
你怎么理解
onPostExecute()没有被调用? -
返回空值?可能是罪魁祸首?尝试使用登录 onPostExecute 进行调试
-
这里有什么原因你没有在
doInBackground()中返回List<InstagramData>吗?将其设置为字段不是线程安全的。可能只是工作线程设置了字段,但 ui 线程没有看到更改的值。 -
另外,您似乎嵌套了
AsyncTask而不使其成为静态,这会造成内存泄漏。 -
@hrskrs:我在 onPostExecute 的超级调用之前添加了一个日志,它没有被打印出来。
标签: android android-fragments android-activity android-asynctask