在继续下一步之前,我想从我的onComplete函数中获取一个布尔值。
我的问题是,当我的布尔值(isLoginSucces)对我的代码至关重要时,当代码进入该部分时,它只会得到错误的值,因为onComplete函数在更改布尔值时并没有到达该点。 / p>
我尝试了异步功能,但是它没有用,还有AtomicBoolean,也没有用。
在那之后,我什至放了Thread.sleep(10000)。在那段时间(10秒)中,它肯定会更改该值,但是也不能正常工作,仍然是错误的,我不明白。
private String loginButtonClicked () {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
...
LoginFragment.this.isLoginSucces = true;
Log.d("boolean", "boolean value in onComplete: " + isLoginSucces);
} else {
...
LoginFragment.this.isLoginSucces = false;
}
}
});
//HERE I tried Thread.sleep(10000);
Log.d("boolean", "boolean value after function: " + isLoginSucces);
if (LoginFragment.this.isLoginSucces)
return email;
else
return null;
}
日志输出为:
2019-03-29 18:45:12 D /布尔值:函数后的布尔值:假
2019-03-29 18:45:14 D /布尔值:onComplete中的布尔值:true
答案 0 :(得分:0)
public void methodThatCallsLoginButtonClicked() {
// code before calling loginButtonClicked
loginButtonClicked();
// nothing else that needs the value from login button clicked should be here
}
public void afterLogin(boolean result) {
// any code that needs the value of the login callback
}
private void loginButtonClicked () {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
afterLogin(task.isSuccessful());
}
});
}
答案 1 :(得分:-1)
声明
String str_email = "";
位于代码的顶部。
将依赖代码插入oncomplete方法中,以删除return语句并更改为:
private String loginButtonClicked () {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
...
LoginFragment.this.isLoginSucces = true;
Log.d("boolean", "boolean value in onComplete: " + isLoginSucces);
} else {
...
LoginFragment.this.isLoginSucces = false;
}
if (LoginFragment.this.isLoginSucces)
str_email = email;
else
str_email = ";
});
}
使用
完成代码if(!str_email.equals("")){
//if str_email is different from ""
}