how do i send data back from onPostExecute in an AsyncTask?

前端 未结 2 524
清歌不尽
清歌不尽 2020-11-27 21:39

my issue is the same as this Instance variable of Activity not being set in onPostExecute of AsyncTask or how to return data from AsyncTask to main UI thread but i want to

2条回答
  •  时光取名叫无心
    2020-11-27 22:35

    This depends on your class structure, but if your AsyncTask is a class within your Activity then you can reference methods of that activity. What you would do is in your onPostExecute method call a function of your Activity that passes some data that was retrieved in the AsyncTask to the activity where you can then use it..

    The code would look like this

    class YourActivity extends Activity {
       private static final int DIALOG_LOADING = 1;
    
       public void onCreate(Bundle savedState) {
         setContentView(R.layout.yourlayout);
         showDialog(DIALOG_LOADING);     
         new LongRunningTask1().execute(1,2,3);
    
       } 
    
       protected Dialog onCreateDialog(int dialogId) {
         switch(dialogId) {
           case DIALOG_LOADING:
               ProgressDialog pDialog = new ProgressDialog(this);
               pDialog.setTitle("Loading Data");
               pDialog.setMessage("Loading Data, please wait...");
               return pDialog;
            default:
                return super.onCreateDialog(dialogId);
          }      
       }
    
       private void onBackgroundTaskDataObtained(List results) {
          dismissDialog(DIALOG_LOADING);
         //do stuff with the results here..
       }
    
       private class LongRunningTask extends AsyncTask> {
            @Override
            protected void onPreExecute() {
              //do pre execute stuff
            }
    
            @Override
            protected List doInBackground(Long... params) {
                List myData = new ArrayList(); 
                for (int i = 0; i < params.length; i++) {
                    try {
                        Thread.sleep(params[i] * 1000);
                        myData.add("Some Data" + i);
                    } catch(InterruptedException ex) {
                    }                
                }
                return myData;
            }
    
            @Override
            protected void onPostExecute(List result) {
                YourActivity.this.onBackgroundTaskDataObtained(result);
            }    
        }
    
    }
    

    So the typical flow is like this, set the view of the current page, and then show a progress dialog. Right after that start the async task (or whenever, it doesn't matter really).

    After your async task is complete, call a function of the activity and pass it the data. Don't use shared data within the async task or you risk issues with threading.. Instead once you are done with it pass it to the activity. If you want to update the view progressively while doing work you can use on onProgressUpdate

提交回复
热议问题