gpt4 book ai didi

android - OnCompleteListener 在另一个类中获取结果

转载 作者:行者123 更新时间:2023-11-29 02:28:27 40 4
gpt4 key购买 nike

我有一个 MyActivityFragmentA 组成和 FragmentBMyActivityPresenter . fragment A:

@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];
}

因为操作是异步的,Task<AuthResult>当我尝试从方法 createAccount() 获取 returnCode 时不完整在Fragment (所以我总是得到 0)。在任务完成或以某种方式重组代码后获取值(value)的最佳方法是什么?

最佳答案

最好的方法是在您的 View 中调用一个方法,就像您在调用 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();
}
});
}

并在您的 Activity 界面中添加:

void showResult(int resultCode);

最后,在您实现接口(interface)的 Activity/fragment 中,您需要覆盖:

@Override
public void showResult(int resultCode){
//do something with resultCode
}

关于android - OnCompleteListener 在另一个类中获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50899160/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com