【问题标题】:How to set Callbacks on PhoneAuthOptions in Firebase PhoneAuth?如何在 Firebase PhoneAuth 中的 PhoneAuthOptions 上设置回调?
【发布时间】:2021-08-02 01:26:55
【问题描述】:

“我刚开始学习 Firebase”

我确实在 PhoneAuthOptions 中设置了回调,但我一直收到错误:

java.lang.NullPointerException:您必须在 PhoneAuthOptions 上指定回调。请调用#setCallbacks()。

这是我的第一个活动,我从中获取用户的电话号码并将其传递给第二个活动:

public class SendOTPActivity extends AppCompatActivity {

private EditText mPhoneNumber;
private Button mBtnSendOtp;
String phoneNumber;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_o_t_p);

    mPhoneNumber = findViewById(R.id.phone_number);
    mBtnSendOtp = findViewById(R.id.btn_send_otp);

    phoneNumber = mPhoneNumber.getText().toString();

    mBtnSendOtp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(),VerifyOTPActivity.class);
            intent.putExtra("PHONE_NUMBER",phoneNumber);
            startActivity(intent);

            mBtnSendOtp.setEnabled(false);
        }
    });
}

}

这是第二个活动(验证活动):

public class VerifyOTPActivity extends AppCompatActivity {

private EditText mOtpCode;
private Button mBtnVerifyOtp;
private TextView textView;
private ProgressBar progressBar;

private String phoneNumber;
private String code;

private FirebaseAuth mAuth;

private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;

private  String mVerificationId;

private PhoneAuthProvider.ForceResendingToken mResendToken;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_verify_o_t_p);

    mAuth = FirebaseAuth.getInstance();

    mOtpCode = findViewById(R.id.otp_code);
    mBtnVerifyOtp = findViewById(R.id.btn_verify_otp);
    textView = findViewById(R.id.text_view);
    progressBar = findViewById(R.id.progress_bar);

    phoneNumber = getIntent().getStringExtra("PHONE_NUMBER");
    code = mOtpCode.getText().toString();

    textView.setText("An OTP has been sent to +91 "+phoneNumber);

    startPhoneNumberVerification(phoneNumber);

    mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
            String code = phoneAuthCredential.getSmsCode();
            if (code!=null){
                progressBar.setVisibility(View.VISIBLE);
            }
            signInWithPhoneAuthCredential(phoneAuthCredential);
        }

        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            if (e instanceof FirebaseAuthInvalidCredentialsException) {
                // Invalid request
                Toast.makeText(VerifyOTPActivity.this, "Provided phone number might not be correct", Toast.LENGTH_SHORT).show();
            } else if (e instanceof FirebaseTooManyRequestsException) {
                // The SMS quota for the project has been exceeded
                Toast.makeText(VerifyOTPActivity.this, "Some error has occurred please try again later!", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken token) {
            mVerificationId = s;
            mResendToken = token;
        }
    };
}

@Override
protected void onStart() {
    super.onStart();
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
}

private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
    mAuth.signInWithCredential(phoneAuthCredential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information

                        Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);

                        FirebaseUser user = task.getResult().getUser();
                        // Update UI
                    } else {
                        // Sign in failed, display a message and update the UI
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            Toast.makeText(VerifyOTPActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                            // The verification code entered was invalid
                        }
                    }
                }
            });
}

private void startPhoneNumberVerification(String phoneNumber){
    PhoneAuthOptions options =
            PhoneAuthOptions.newBuilder(mAuth)
                    .setPhoneNumber("+91"+phoneNumber)
                    .setTimeout(60L, TimeUnit.SECONDS)
                    .setActivity(this)
                    .setCallbacks(mCallbacks)
                    .build();
    PhoneAuthProvider.verifyPhoneNumber(options);
}

【问题讨论】:

    标签: java firebase android-studio firebase-authentication


    【解决方案1】:

    onCreate 中,您在创建OnVerificationStateChangedCallbacks 之前调用startPhoneNumberVerification(phoneNumber);。尝试将startPhoneNumberVerification(phoneNumber); 移动到创建回调的块下方。那应该摆脱NullPointerException

    【讨论】:

    • 感谢您抽出宝贵时间@FelixNovovic,成功了。又发生了一个错误,FirebaseAuthInvalidCredentialsException,这是无效电话号码格式的错误。我确实添加了国家代码,为什么会出现这个错误?
    • 如果答案解决了您的问题,请考虑将其标记为已接受的答案。进一步询问会产生一个新问题。我不知道您实际上向 Firebase 发送了什么,所以我只能将您推荐给相关的documentation
    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 2019-10-20
    • 2019-08-01
    • 2019-11-09
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多