Home >Java >javaTutorial >How Can I Get a Boolean Result from an Android AsyncTask Performing FTP Operations?
In your Android application, you're using AsyncTasks to perform FTP operations. However, you're facing a challenge in returning a boolean value indicating whether the connection is successful.
Originally, your code used ftpConnect to establish the connection synchronously and stored the result in a boolean variable (status). However, with AsyncTasks, you're attempting to perform the operation asynchronously.
To return a boolean value from your AsyncTask, consider implementing an interface:
public interface MyInterface { public void myMethod(boolean result); }
Implement this interface in your AsyncTask and pass an instance of it as a parameter to the constructor:
public class AsyncConnectTask extends AsyncTask<Void, Void, Boolean> { private MyInterface mListener; public AsyncConnectTask(Context context, String address, String user, String pass, int port, MyInterface mListener) { mContext = context; _address = address; _user = user; _pass = pass; _port = port; this.mListener = mListener; } @Override protected Boolean doInBackground(Void... params) { .... return result; } @Override protected void onPostExecute(Boolean result) { if (mListener != null) mListener.myMethod(result); } }
In your activity or fragment, create an instance of the AsyncTask and pass your interface implementation as a parameter:
AsyncConnectTask task = new AsyncConnectTask(SiteManager.this, _address, _username, _password, _port, new MyInterface() { @Override public void myMethod(boolean result) { if (result == true) { Toast.makeText(SiteManager.this, "Connection Succesful", Toast.LENGTH_LONG).show(); } else { Toast.makeText(SiteManager.this, "Connection Failed:" + status, Toast.LENGTH_LONG).show(); } } }); task.execute();
In the myMethod implementation, you can handle the result as required. Note that this method will be invoked on the UI thread
The above is the detailed content of How Can I Get a Boolean Result from an Android AsyncTask Performing FTP Operations?. For more information, please follow other related articles on the PHP Chinese website!