0

這是我第一次遇到AsyncTask onPostExecute()問題。我有其他AsyncTask在Fragment中工作。對於此特定片段類,AsyncTask doInBackground()完成其執行,但onPostExecute()不稱爲。我嘗試從doInBackground返回數據,並且在AsyncTask中分配給全局變量。但對於這兩種情況,onPostExecute沒有調用。AsyncTask onPostExecute()不是從片段類調用,但在Activity類中工作

這是我的代碼片段。

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未針對兩個asyncTasks進行調用。

+0

你如何理解'onPostExecute()'沒有被調用? – hrskrs

+0

返回null?可能是罪魁禍首?嘗試使用onPostExecute中的日誌進行調試 – Skynet

+1

這裏有什麼原因,您不在'doInBackground()'中返回'List '?將其設置爲字段不是線程安全的。它可能只是可能的工作線程已設置字段,但UI線程沒有看到更改的值。 –

回答

0

已解決 .. Inside onActivityCreated()中,存在一個while循環,其條件在onPostExecute()完成後將失敗。如果沒有錯,我認爲由於這個while循環,onPostExecute保留在主線程中,並等待onActivityCreated完成。

相關問題