AsyncTask - after execution, how to update view?

前端 未结 3 685
北恋
北恋 2020-12-16 19:37

In the onCreate() event of an Activity, I have started an AsyncTask to retrieve Product data from a database. After this has been completed successfully, how can I update th

相关标签:
3条回答
  • 2020-12-16 20:18

    I am guessing the question is more about how to get hold of the UI View if the asyncTask is in a separate file .

    In that case you have to pass the context to the Async task and use that to get the view.

    class MyAsyncTask extends AsyncTask<URL, Integer, Long> {
    
        Activity mActivity;
    
        public MyAsyncTask(Activity activity) {
           mActivity = ativity;
        }
    

    And then in your onPostExecute use

    int id = mActivity.findViewById(...);
    

    Remember you cannot update the View from "doInBackground" since its not the UI thread.

    0 讨论(0)
  • 2020-12-16 20:19

    If you want to update the view from async after complete process in then you can use

    protected void onPostExecute(String result)
        {
            textView.setText(result);
        }
    

    But if you want to update data while running background process then use. For ex...

    protected Long doInBackground(URL... urls) {
             int count = urls.length;
             long totalSize = 0;
             for (int i = 0; i < count; i++) {
                 totalSize += Downloader.downloadFile(urls[i]);
                 publishProgress((int) ((i / (float) count) * 100));<------
             }
             return totalSize;
         }
    
         protected void onProgressUpdate(Integer... progress) {  <-------
             setProgressPercent(progress[0]);
         }
    

    for more detail see this link Hope this will help you...!

    0 讨论(0)
  • 2020-12-16 20:30

    In your AsyncTask class, add a onPostExecute method. This method executes on the UI thread and can update any UI component.

    class GetProductDetails extends AsyncTask<...> 
    {
        ...
        private TextView textView;
        ...
        protected void onPostExecute(String result)
        {
            textView.setText(result);
        }
    }
    

    (The result parameter is the value returned from the doInBackground method of your class.)

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