How to return ArrayList from AsyncTask to another class?

后端 未结 7 727
被撕碎了的回忆
被撕碎了的回忆 2021-01-21 20:01

i want to get Ftp folders list from server using AsyncTask and return folders names ArrayList to main class and update spinner adapter.

In main class i got spinner with

7条回答
  •  忘掉有多难
    2021-01-21 20:07

    I assume you don't want a spinner while fetching data, but rather to fill your spinner with data from the background task? Returning data from AsyncTask commonly relies on this pattern, using interface.

    1) Create an interface so that you can post back your results: (This class you can either create in separate file or just declare it in either class)

    public interface ReturnData{
        void handleReturnData(ArrayList list);
    }
    

    2) Implement the ReturnData interface in your main class:

    public class MyMainClass extends Activity implements ReturnData{
    
        AsyncTask ftpTeacher = new FtpTeacher();//declare your async task
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            ftpTeacher.returnData = this; //set this class as receiver for return data
            //set up adapters etc, just like you do now
            ...
        }
    
    
    
         //Your new data will be returned here - update your current adapter with new list
         @Override
         void handleReturnData(ArrayList list){
              directoriesTeacher = list; //assign new data
              dataAdapterTeacher.notifyDataSetChanged();  //Tell adapter it has new data = forces redraw
         }
    
         ....
    }
    

    3) In your AsyncTask class:

    public class FtpTeacher extends AsyncTask, Void, ArrayList> {
        private static final String TAG = "MyFTPClient";
        public FTPClient mFTPClient = null; 
        ArrayList ftpTeacher = new ArrayList();
        public ReturnData returnData; // <--- PUBLIC
        ...
     }
    

    4) Finally, to return data:

    protected ArrayList[] onPostExecute(ArrayList... result) {
        returnData.handleReturnData(result);
    }
    

提交回复
热议问题