You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Firebase PhoneAuthOptions与数据库共存异常排查

Firebase手机号登录与数据库共存问题解决方案

问题分析

  1. OtpActivity崩溃原因:崩溃日志显示NullPointerException来自PhoneAuthOptions$Builder初始化,根源是firebaseAuth实例未初始化就传入PhoneAuthOptions.newBuilder()方法。
  2. 数据库功能异常:引入Firebase BOM后版本统一,需适配数据库操作代码,同时检查用户认证状态、数据库规则配置是否合规。

解决方案

1. 修复OtpActivity的NullPointerException

在OtpActivity的onCreate方法中,调用sendVerificationCode前先初始化FirebaseAuth实例:

修改后的OtpActivity.onCreate代码:

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

    initialize();

    // 提前初始化FirebaseAuth实例
    firebaseAuth = FirebaseAuth.getInstance();

    phoneNumber = getIntent().getStringExtra("phone_number");
    sendVerificationCode(phoneNumber);

    customProgressDialog = new CustomProgressDialog(this);
    textError.setVisibility(View.INVISIBLE);
    pinView.requestFocus();
    getSupportActionBar().setTitle("Verify your phone number");
    textSub.setText("Enter the 6-digit OTP sent to your phone number " + phoneNumber + " to verify");

    verifyButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            verifyCode(pinView.getText().toString());
        }
    });
}

2. 修复数据库功能异常

  • 添加用户登录状态校验:获取用户UID前先判断当前用户是否已认证,避免空指针:
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() != null){
    currentUserId = firebaseAuth.getCurrentUser().getUid();
    userProfileImageRef = FirebaseStorage.getInstance().getReference().child("profile images");
    userDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId);
} else {
    // 跳转到登录页面或提示用户登录
    Intent loginIntent = new Intent(this, LoginActivity.class);
    startActivity(loginIntent);
    finish();
}
  • 检查Firebase数据库规则:确保控制台中数据库规则允许已认证用户读写,示例规则:
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}
  • 确认BOM版本兼容性:当前使用的firebase-bom:31.2.3为稳定版本,所有Firebase组件通过BOM统一版本,无需单独指定组件版本,避免版本冲突。

3. 其他注意事项

  • 确保google-services.json文件正确放置在app/目录下,配置与Firebase控制台一致;
  • 清理项目缓存并重新构建:执行Build > Clean Project和Build > Rebuild Project,解决依赖缓存问题。

内容的提问来源于stack exchange,提问作者Surya Pratap Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 04:07:36