How to Return a Boolean from Asynctask

How do I return a boolean from AsyncTask?

public interface MyInterface {
public void myMethod(boolean result);
}

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

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

If you call myMethod from onPostExecute the code inside it will run on the UI Thread. Otherwise you need to post a Runnable through a Handler

Returning boolean from onPostExecute and doInBackground

Change the onPostExecute() argument type to Boolean and then tell who would be interested in the result what happened.

For this last part you can have an interface and have that someone (intereste class) implement it.

public class Login extends AsyncTask<String, Boolean, Boolean> {

private LoginListener listener;

public Login(Application application, LoginListener listener){
repository = new Repository(application);
this.listener = listener;
}

@Override
protected Boolean doInBackground(String... body){
try {
user = repository.getUser(body[0], body[1]);
if (user != null)
return true; //wont work
else {
return false;
}
}
catch(Exception e){
return null;
}
}

protected void onPostExecute(Boolean result) {
listener.onLoginPerformed(result)
}



public static interface LoginListener{
public void onLoginPerformed(Boolean result);
}
}

Then suppose you want MainActivity to react upon the login:

public class MainActivity extends AppCompatActitvity implements LoginListener{
....
// When you create the Login object, in onCreate() for example:
// new Login(application, this); // this is the activity acting as listener...

@Override public void onLoginPerformed(Boolean result){
// do what you want to do with the result in Main Activity
}

}

AsyncTask to return a boolean? Best way to implement?

here's a sample code:

new AsyncTask<Void, Void, Boolean>()
{
@Override
protected Boolean doInBackground(Void... p)
{
return isConnected();
}

@Override
protected void onPostExecute(Boolean result)
{
//this is code for the UI thread, now that it knows what is the result.
}
}.execute();

Boolean Return from AsyncTask in Android

1) You don't have a response variable anywhere, and doInBackground has returned null instead of any response, so not clear how you got that value.

 delegate.processFinish(response.toString());

2) You can't return from that function. And your app crashes probably because Boolean's can be null. boolean's cannot. However, you should not attempt to make a global variable here because that's not how asynchronous code should run.

What you need is to pass the callback through the function

private void checkDataRegistrationByServer(String data, CallSoap.AsyncResponse callback) { 
CallSoap nickNameExistCall = new CallSoap(RegistrationActivity.this, callback);
CallSoapParams callParams = new CallSoapParams(data);
nickNameExistCall.execute(callParams);
}

Elsewhere...

final String nick = NICKNAME_EXIST;
checkDataRegistrationByServer(nick, new CallSoap.AsyncResponse() {

@Override
public void processFinish(String response) {
Log.d("Response From AsyncTask:", output);
boolean exists = !response.equals(FALSE_RESPONSE);
if (!exists) {
Toast.makeText(getApplicationContext(), output + " - NickNameExistCall - Nick " + nick + " doesn't exist", Toast.LENGTH_SHORT).show();
}
}
});

Note: If you make your AsyncTask just return a Boolean in the AsyncResponse you can shorten this code some.

AsyncTask return a boolean while retrieving information from a Json

To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .

An AsyncTask is started via the execute() method.

The execute() method calls the doInBackground() and the onPostExecute() method.

TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.

In your case you are passing Void to your AsyncTask : isCollectorRegistered extends AsyncTask<Void, Void, Void> so you can't get your result from the thread.
please read this tutorial to a deep understand of the AsyncTask in Android

Returning Boolean value from Asynctask in Android

Change the whole thing to (blind coding):

class checking extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean a;
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(l1);
HttpResponse response;
try {
response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
a = false;
} else {
a = true;
}
return a;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
Toast.makeText(getApplicationContext(), (result ? "Yes" : "No"), Toast.LENGTH_LONG).show();
}
}

Kotlin - Return a Boolean from an async task that does not return a boolean

You can do this with CompletableDeferred. Try something like that:

suspend fun login(email: String, password: String): Boolean {
val completableDeferred = CompletableDeferred<Boolean>()
val credentials = Credentials.emailPassword(email, password)
app.loginAsync(credentials) {
completableDeferred.complete(it.isSuccess)
}
return completableDeferred.await()
}

Android: How to get boolean result from AsyncTask?

new InternetCheck(new InternetCheck.Consumer() {
@Override
public void accept(Boolean connected) {
if (connected) {
Log.d("TAG", "Internet is connected");
} else {
Log.d("TAG", "Internet is not connected");
}
}
}).execute();


Related Topics



Leave a reply



Submit