Rémi Rémi - 17 days ago 4
Android Question

doInTheBackground doesn't wait for function to finish?

I am trying to put together a login screen using the Stormpath framework in android. I used the standard Login screen provided in android studio and only modified the UserLoginTask. My problem is that it doesn't seem to wait for my call to Stormpath to finish. As soon as the class is called it goes straight in exectures doInBackground and then goes straight to onPostExecute. Here is my class:

public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

private final String mEmail;
private final String mPassword;
private boolean loginResult;
String errorMessage;


UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}

@Override
protected Boolean doInBackground(Void... params) {
Stormpath.login(mEmail, mPassword, new StormpathCallback<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d("debug", "sucess");
loginResult = true;
}

@Override
public void onFailure(StormpathError error) {
errorMessage = error.message();
Log.d("debug", "Error: " + error.message());
loginResult = false;
}
});
return loginResult;
}

@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);

if (success) {
finish();
} else {
Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}

@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}

Answer

Since Stormpath.login() uses a callback, most likely it's already doing the network call on a background thread and returns you the result via the callback. If this is the case, then you don't really need an AsyncTask.