如何将ArrayList从AsyncTask返回到另一个类?

时间:2014-03-11 12:31:28

标签: java android android-asynctask ftp-client

我希望使用AsyncTask从服务器获取Ftp文件夹列表,并将文件夹名称ArrayList返回到主类并更新微调器适配器。

在主要课程中,我得到了带适配器的微调器

//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);

在AsyncTask中:

    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更新器?

7 个答案:

答案 0 :(得分:3)

- PSEUDO CODE -

创建自定义interface,如下所示:

public interface IAsyncTask {

    void IAmFinished(ArrayList<Object> arrayList);

}

AsyncTask添加构造函数:

private IAsyncTask asyncTaskListener;

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

PostExecute的{​​{1}}中:

AsyncTask

启动public void onPostExecute(List<String> list) { asyncTaskListener.IAmFinished(list); } 的{​​{1}}:

Activity

实施界面:

AsyncTask

实施方法:

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

答案 1 :(得分:1)

您已将ArrayList 静态设为公开,并将其公开。并按您的班级名称使用它。并在onPostExecute()中填充您的ArrayList;像

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

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

      YourClassName.directoriesTeacher.addAll(result);

     }

答案 2 :(得分:1)

我假设您在获取数据时不需要微调器,而是使用后台任务中的数据填充微调器?从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);
}

答案 3 :(得分:0)

在你的主,你调用AsyncTask的地方,覆盖onPostExecute方法并将你的适配器东西放在那里。它在UI线程上被调用,所以它是保存的。

所以,在调用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();

答案 4 :(得分:0)

onPostExecute方法在UI线程中运行。您可以将postexecute()中的结果分配给main方法中的arraylist。通过调用notifydatasetChanged更新适配器来更新列表视图。

答案 5 :(得分:0)

实施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 

    }

答案 6 :(得分:0)

在AsyncTask中,您可以拥有一个与您的活动相同的成员(MyActivity m_activity)。

在AsyncTask构造函数中,设置MyActivity参数并将其记录在m_activity中。

在你的onPostExecute中运行一个刷新你的微调器适配器的活动方法:m_activity.updateSpinner(ftpTeacher );