我想使用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 Updater?
您已经将ArrayList 设为 static ,也将其设为public。并以您的班级名称使用该名称。并在onPostExecute()中填充您的ArrayList;喜欢
protected void onPostExecute(ArrayList<String>... result) { if(YourClassName.directoriesTeacher.size()>0) { YourClassName.directoriesTeacher.clear(); } YourClassName.directoriesTeacher.addAll(result); }