[英]Doing something after AsyncTask finishes
我正在開發一個 android 應用程序,它使用 Jsoup 來檢索 web 內容。 為了執行這個,我使用了單獨的AsyncTask
類。 我需要在AsyncTask
完成后顯示檢索到的結果。 doInBackground
方法將檢索到的數據存儲到一個數組中。
ScheduleExtractor scheduleExtractor = new ScheduleExtractor();
scheduleExtractor.execute();
if(myArray.length==0){
///
}else{
//show results
}
但是,當我在調用方法Asynctask.execute()
后嘗試訪問數組時,數組沒有元素。 那么,有沒有辦法確保在完成AsyncTask
方法后才能訪問數組? 謝謝你。
顧名思義, AsyncTask
代表您是否異步工作,這意味着對execute()
的調用在不同的線程中啟動進程,而代碼的 rest 在調用execute()
后立即在您自己的線程上繼續運行。
如果您希望AsyncTask
有最終結果,您應該重寫onPostExecute(Result)
方法並在那里檢查數組的長度。 這是一個簡單的示例(假設最終結果類型是int[]
:
class ScheduleExtractor extends AsyncTask<Void, Void, int[]> {
@Override
protected int[] doInBackground(Void... params) {
// Process your retrieved data and return the result here
}
@Override
protected void onPostExecute(int[] arrayResult) {
if(arrayResult.length==0) {
// Your code here
} else {
// Show results
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.