AsyncTask return value only after using get() method

后端 未结 1 1789
一生所求
一生所求 2021-01-27 16:31

I\'ve created activity, which should return array of GeoPoint after user clicked the button. Code which perform http request and parse answer is extracted to AsyncTask. In the <

相关标签:
1条回答
  • 2021-01-27 17:13

    An AsyncTask does exactly what it's name suggests - the doInBackground(...) method runs asynchronously on a separate thread while the code in onCreate(...) continues to run.

    In your code here...

    mat.execute(query);
    
    if (overlayList.size() > 0){
        tv1.setText("List is OK!");
    }
    

    ...the if condition is checked immediately after you call mat.execute(query). In other words, your AsyncTask hasn't had a chance to execute it's doInBackground(...) method.

    Move this code...

    if (overlayList.size() > 0){
        tv1.setText("List is OK!");
    }
    

    ...into the onPostExecute(...) method of your AsyncTask.

    EDIT: As triggs points out in the comment below, calling the get() method of AsyncTask will block the main thread and wait for the result to be returned. This effectively makes using an AsyncTask become a synchronous operation in which case there's no point in using an AsyncTask.

    The only reason I can think of to use the get() method would be from a thread other than the main (UI) thread although I can't think of many reasons to do that.

    0 讨论(0)
提交回复
热议问题