我有一个由FragmentA
、FragmentB
和MyActivityPresenter
组成的MyActivity
。FragmentA:
@OnClick(R.id.proceed_sign_up)
public void onBtnProceedSignUp(){
if(checkInputSignUp()){
int returnCode = presenter.createAccount(email, pswd, nick);
//handle return code: show error on EditTexts,etc.
}
}
演示者:
public int createAccount(String email, String password, final String nickname) {
final int[] code = new int[1];
activity.showLoading(true);
firebaseUserService.createUserWithEmail(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
processLogin(task.getResult().getUser(), task.getResult().getUser().getProviderData().get(1), nickname);
} else {
Log.d("Create not success", task.getException().toString());
switch (task.getException().getMessage()) {
case "The email address is already in use by another account":
code[0] = 10;
break;
default:
code[0] = 20;
break;
}
}
activity.showLoading(false);
activity.showLoginFail();
}
});
return code[0];
}
因为操作是异步的,所以当我尝试从Fragment
中的createAccount()
方法获取returnCode时,Fragment
不会完成(所以我总是得到0)。在任务完成或以某种方式重新组织代码后,获取价值的最佳方法是什么?
发布于 2018-06-18 02:01:26
最好的方法是在视图中调用一个方法,就像调用showLoading和hideLoading方法时已经做的那样:
public void createAccount(String email, String password, final String nickname) {
final int[] code = new int[1];
activity.showLoading(true);
firebaseUserService.createUserWithEmail(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
processLogin(task.getResult().getUser(),
task.getResult().getUser().getProviderData().get(1), nickname);
} else {
Log.d("Create not success", task.getException().toString());
switch (task.getException().getMessage()) {
case "The email address is already in use by another account":
code[0] = 10;
break;
default:
code[0] = 20;
break;
}
activity.showResult(code[0]);
}
activity.showLoading(false);
activity.showLoginFail();
}
});
}
并在你的活动实现的接口中添加:
void showResult(int resultCode);
最后,在实现接口的activity/fragment中,您需要覆盖:
@Override
public void showResult(int resultCode){
//do something with resultCode
}
https://stackoverflow.com/questions/50899160
复制相似问题