首页 > 解决方案 > 如何在 Firebase PhoneAuth 中的 PhoneAuthOptions 上设置回调?

问题描述

“我刚开始学习 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);
}

标签: javafirebaseandroid-studiofirebase-authentication

解决方案


onCreatestartPhoneNumberVerification(phoneNumber);创建您的OnVerificationStateChangedCallbacks. 尝试移动startPhoneNumberVerification(phoneNumber);到创建回调的块下方。那应该摆脱NullPointerException.


推荐阅读