java—如何将arraylist从asynctask返回到另一个类?

6ljaweal  于 2021-07-09  发布在  Java
关注(0)|答案(7)|浏览(353)

我想使用asynctask从服务器获取ftp文件夹列表,并将文件夹名称arraylist返回到主类并更新spinner适配器。
在主课上我有一个带转接器的旋转器

//the array i want to update in AsyncTask
static ArrayList<String> directoriesTeacher = new ArrayList<String>();

//The adapter
createfile_spinTeacher = (Spinner) findViewById(R.id.createfile_spinTeacher);   
final ArrayAdapter<String> dataAdapterTeacher = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,directoriesTeacher);
dataAdapterTeacher.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
createfile_spinTeacher.setAdapter(dataAdapterTeacher);

异步任务中的任务:

package com.nedoGarazas.learnanylanguage;

    import java.util.ArrayList;

    import org.apache.commons.net.ftp.FTP;
    import org.apache.commons.net.ftp.FTPClient;
    import org.apache.commons.net.ftp.FTPFile;
    import org.apache.commons.net.ftp.FTPReply;

    import android.os.AsyncTask;
    import android.util.Log;

    public class FtpTeacher extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
    private static final String TAG = "MyFTPClient";
    public FTPClient mFTPClient = null; 
     ArrayList<String> ftpTeacher = new ArrayList<String>();
    @Override
    protected ArrayList<String> doInBackground(ArrayList<String>... params) {
        {                       
            try {
                mFTPClient = new FTPClient();
         // connecting to the host
                mFTPClient.connect("host.ftp.com", 21);

          // now check the reply code, if positive mean connection success
                if     (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
      // login using username & password
                    boolean status = mFTPClient.login("admin", "admin");
                    if(status == true){

                            try {
                                FTPFile[] ftpFiles = mFTPClient.listFiles("/Wordsftp/");
                                int length = ftpFiles.length;

                                for (int i = 0; i < length; i++) {
                                    String name = ftpFiles[i].getName();
                                    boolean isDirectory = ftpFiles[i].isDirectory();

                                    if (isDirectory) {
//adding to arraylist
                                        ftpTeacher.add(name);
                                        Log.i(TAG, "Yra : " + name);
                                    }
                                    else {
                                        Log.i(TAG, "Directory : " + name);

                                }
                             }
                            } catch(Exception e) {
                            e.printStackTrace();
                        }

                    mFTPClient.setFileType(FTP.ASCII_FILE_TYPE);
                    mFTPClient.enterLocalPassiveMode();

}
                }
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host ");
}
return ftpTeacher;
} 
            }

    protected ArrayList<String>[] onPostExecute(ArrayList<String>... result) {
        ////How to return?

    }

    }

那么,我应该如何用主类中的arraylist替换asynctask中的arraylist并直接更新spinner更新程序呢?

qgelzfjb

qgelzfjb1#

--伪码--
创建自定义 interface 具体如下:

public interface IAsyncTask {

    void IAmFinished(ArrayList<Object> arrayList);

}

将构造函数添加到 AsyncTask :

private IAsyncTask asyncTaskListener;

public MyAsyncTask(IAsyncTask asyncTaskListener){
     this.asyncTaskListener = asyncTaskListener;
}

在你的 PostExecuteAsyncTask :

public void onPostExecute(List<String> list) {
    asyncTaskListener.IAmFinished(list);
}

在你的 Activity 这就开始了你的人生 AsyncTask :

MyAsyncTask asyncTask = new MyAsyncTask(this);
asyncTask.execute(..);

实现接口:

public class MyActivity implements IAsyncTask

实施方法:

public void IAmFinished(ArrayList<Object> list){
    // Do whatever you want with your returned object
}
6rvt4ljy

6rvt4ljy2#

在main中,在调用asynctask的地方,重写onpostexecute方法并将适配器的内容放在其中。它在ui线程上被调用,所以它是save。
所以在调用asynctask的地方

new FTPTeacher() {

 public void onPostExecute(List<String> list) {

     createfile_spinTeacher = (Spinner) findViewById(R.id.createfile_spinTeacher);   
     final ArrayAdapter<String> dataAdapterTeacher = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
     dataAdapterTeacher.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     createfile_spinTeacher.setAdapter(dataAdapterTeacher);

 }

}.execute();
oyt4ldly

oyt4ldly3#

你已经让你的arraylist静态了,也让它公开。用你的班级名称。并在onpostexecute()中填充arraylist;喜欢

protected void onPostExecute(ArrayList<String>... result) {

    if(YourClassName.directoriesTeacher.size()>0)
     {
       YourClassName.directoriesTeacher.clear();
      }

      YourClassName.directoriesTeacher.addAll(result);

     }
mbskvtky

mbskvtky4#

我假设您不希望在获取数据时使用微调器,而是希望用后台任务中的数据填充微调器?从asynctask返回数据通常依赖于这个模式,使用接口。
1) 创建一个接口,这样就可以发回结果:(这个类可以在单独的文件中创建,也可以在任何一个类中声明)

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

2) 在主类中实现returndata接口:

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<String> list){
          directoriesTeacher = list; //assign new data
          dataAdapterTeacher.notifyDataSetChanged();  //Tell adapter it has new data = forces redraw
     }

     ....
}

3) 在asynctask类中:

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

4) 最后,要返回数据:

protected ArrayList<String>[] onPostExecute(ArrayList<String>... result) {
    returnData.handleReturnData(result);
}
wwodge7n

wwodge7n5#

实施 listener 经过 ArrayList 用这个监听程序返回你的 ArrayList .

public interface TaskListener {
    public void onSuccess(ArrayList<String> result);

}

在调用异步任务执行操作时,创建 TaskListener 具体如下:

TaskListener listener = new TaskListener() {

        @Override
        public void onSuccess(ArrayList<String> result) {
               // Your result will come here
        }
    };

把这个传过来 listener 对象作为异步任务构造函数的参数。并创建 TaskListener 在异步任务本身中。分配 TaskListener 全局示例的构造函数中的参数。
然后在 onPostExecute 异步任务类的名称:

protected ArrayList<String>[] onPostExecute(ArrayList<String>... result) {
        this.taskListenerGlobalInstance(result); // this will invoke the call back method 

    }
jfgube3f

jfgube3f6#

onpostexecute方法在ui线程中运行。可以将postexecute()中的结果赋给main方法中的arraylist。通过调用notifydatasetchanged更新listview来更新适配器。

vvppvyoh

vvppvyoh7#

在asynctask中,可以有一个成员(myactivity m\u activity)与活动的类相同。
在asynctask构造函数中,设置myactivity参数并将其记录在m\u activity中。
在onpostexecute中,运行活动的方法以刷新微调器适配器: m_activity.updateSpinner(ftpTeacher );

相关问题