OnCompleteListener在另一个类中获得结果

时间:2018-06-17 17:56:29

标签: android listener mvp

我有一个由MyActivityFragmentA以及FragmentB组成的MyActivityPresenter。 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];
}

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

1 个答案:

答案 0 :(得分:0)

最好的方法是在调用showLoading和hideLoading方法时调用View中的方法:

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

最后,在您实现界面的活动/片段中,您需要覆盖:

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