Home >Java >javaTutorial >How Can I Return a Boolean Value from an Android AsyncTask?

How Can I Return a Boolean Value from an Android AsyncTask?

Susan Sarandon
Susan SarandonOriginal
2024-12-13 18:20:12502browse

How Can I Return a Boolean Value from an Android AsyncTask?

Returning a Boolean from AsyncTask

In Android development, it may be necessary to return a boolean value from an asynchronous task performed by AsyncTask. This is useful in situations where you need to determine the success or failure of a specific operation.

To return a boolean from AsyncTask, you can implement a callback interface. Here's how to do it:

  1. Create a callback interface: Define an interface with a method that accepts a boolean parameter, representing the result of the task.
public interface MyInterface {
    public void myMethod(boolean result);
}
  1. Pass the callback interface to AsyncTask: When creating your AsyncTask, pass the callback interface as an argument.
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;
    }

    // ... (Rest of the AsyncTask code)
}
  1. Implement the callback method in the parent activity: In the parent activity or fragment that initiated the AsyncTask, implement the callback method defined in the interface.
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();

By following these steps, you can effectively return a boolean value from an AsyncTask and handle the result accordingly.

The above is the detailed content of How Can I Return a Boolean Value from an Android AsyncTask?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn