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

Firebase实时数据库未在控制台显示数据问题求助

问题:Firebase实时数据库无法写入用户ID,无报错提示

我尝试从Firebase邮箱/密码认证模块获取用户ID并写入Firebase实时数据库,但数据未在控制台中显示,且无任何报错提示。我已开启邮箱/密码认证功能,数据库规则设置如下:

{ "rules": { ".read": "auth != null", ".write": "auth != null" } }

以下是我的DriverLogin类代码:

public class DriverLogin extends AppCompatActivity { 
    private static final String TAG = "EmailPassword"; 
    private EditText mEmail; 
    private EditText mPass; 
    private FirebaseAuth mAuth; 
    private FirebaseAuth.AuthStateListener firebaseAuthListener; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_driver_login); 
        mAuth = FirebaseAuth.getInstance(); 
        firebaseAuthListener= new FirebaseAuth.AuthStateListener() { 
            @Override 
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
                FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); 
                if(user != null){ 
                    Intent intent = new Intent(DriverLogin.this,DriverMain.class); 
                    startActivity(intent); 
                    finish(); 
                    return; 
                } 
            } 
        }; 

        //editText 
        mEmail = findViewById(R.id.DriverEmail); 
        mPass = findViewById(R.id.DriverPass); 

        //Btn 
        findViewById(R.id.DriverSign).setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View v) { 
                signUp(mEmail.getText().toString(), mPass.getText().toString()); 
            } 
        }); 

        findViewById(R.id.DriverLogbtn).setOnClickListener(new View.OnClickListener() { 
            @Override 
            public void onClick(View v) { 
                signIn(mEmail.getText().toString(), mPass.getText().toString()); 
            } 
        }); 
    } 

    //CreateAccount with Email and Password 
    private void signUp(final String email, final String password) { 
        Log.d(TAG, "CreateAccount:" + email); 
        if (!validateForm()) { 
            return; 
        } 
        mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { 
            @Override 
            public void onComplete(@NonNull Task<AuthResult> task) { 
                if (task.isSuccessful()) { 
                    Log.d(TAG, "createUserWithEmail:success"); 
                    Toast.makeText(DriverLogin.this, "Registered Successfully", Toast.LENGTH_SHORT).show(); 
                } else { 
                    String user_id = mAuth.getCurrentUser().getUid(); 
                    DatabaseReference driverDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(user_id); 
                    driverDb.setValue(true); 
                    Toast.makeText(DriverLogin.this, "Something went wrong", Toast.LENGTH_SHORT).show(); 
                } 
            } 
        }); 
    } 

    //---------------------------------------------LOGIN------------------------------------// 
    //Login Existing Account 
    private void signIn(final String email, final String pass) { 
        Log.d(TAG, "CreateAccount:" + email); 
        if (!validateForm()) { 
            return; 
        } 
        mAuth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { 
            @Override 
            public void onComplete(@NonNull Task<AuthResult> task) { 
                if (task.isSuccessful()) { 
                    Log.d(TAG, "signInWithEmail:success"); 
                    FirebaseUser user = mAuth.getCurrentUser(); 
                    Toast.makeText(DriverLogin.this, "Logged in Successfully", Toast.LENGTH_SHORT).show(); 
                } else { 
                    // If sign in fails, display a message to the user. 
                    Log.w(TAG, "signInWithEmail:failure", task.getException()); 
                    Toast.makeText(DriverLogin.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); 
                } 
                // [END_EXCLUDE] 
            } 
        } ); 
    } 

    @Override 
    protected void onStart() { 
        super.onStart(); 
        mAuth.addAuthStateListener(firebaseAuthListener); 
    } 

    @Override 
    protected void onStop() { 
        super.onStop(); 
        mAuth.removeAuthStateListener(firebaseAuthListener); 
    } 

    //textfield validations 
    private boolean validateForm() { 
        boolean valid = true; 
        String email = mEmail.getText().toString(); 
        if (TextUtils.isEmpty(email)) { 
            mEmail.setError("Required."); 
            valid = false; 
        } else { 
            mEmail.setError(null); 
        } 

        String password = mPass.getText().toString(); 
        if (TextUtils.isEmpty(password)) { 
            mPass.setError("Required."); 
            valid = false; 
        } else { 
            mPass.setError(null); 
        } 

        return valid; 
    } 
} 

以及app模块的build.gradle依赖配置:

dependencies { 
    implementation fileTree(dir: 'libs', include: ['*.jar']) 
    implementation 'com.android.support:appcompat-v7:27.1.1' 
    implementation 'com.android.support.constraint:constraint-layout:1.1.0' 
    implementation 'com.google.firebase:firebase-core:15.0.2' 
    implementation 'com.google.firebase:firebase-database:15.0.0' 
    implementation 'com.google.firebase:firebase-auth:15.1.0' 
    implementation 'com.google.android.gms:play-services-auth:15.0.1' 
    implementation 'com.github.bumptech.glide:glide:4.7.1' 
    implementation 'com.android.support:design:27.1.1' 
    annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1' 
    testImplementation 'junit:junit:4.12' 
    androidTestImplementation 'com.android.support.test:runner:1.0.2' 
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 
} 
apply plugin: 'com.google.gms.google-services' 

请帮忙排查数据无法写入数据库的原因。


问题分析与解决方案

我仔细看了你的代码,很快就找到了几个核心问题,这就是数据没写入数据库的关键原因:

1. 注册逻辑完全搞反了

你的signUp方法里,居然只在注册失败的时候才尝试写入数据库!这完全不符合逻辑——只有当注册成功,用户账号创建完成时,才应该把用户ID写入数据库。而注册失败时,mAuth.getCurrentUser()大概率是null,甚至会抛出空指针异常(你没碰到报错只是没触发这个场景而已)。

修正后的signUp方法应该是这样:

private void signUp(final String email, final String password) { 
    Log.d(TAG, "CreateAccount:" + email); 
    if (!validateForm()) { 
        return; 
    } 
    mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { 
        @Override 
        public void onComplete(@NonNull Task<AuthResult> task) { 
            if (task.isSuccessful()) { 
                Log.d(TAG, "createUserWithEmail:success"); 
                // 注册成功时才写入数据库
                FirebaseUser user = task.getResult().getUser();
                if (user != null) {
                    String user_id = user.getUid(); 
                    DatabaseReference driverDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(user_id); 
                    // 添加成功/失败监听,方便排查问题
                    driverDb.setValue(true)
                        .addOnSuccessListener(unused -> Log.d(TAG, "数据库写入成功"))
                        .addOnFailureListener(e -> Log.e(TAG, "数据库写入失败", e));
                }
                Toast.makeText(DriverLogin.this, "Registered Successfully", Toast.LENGTH_SHORT).show(); 
            } else { 
                Log.w(TAG, "createUserWithEmail:failure", task.getException());
                Toast.makeText(DriverLogin.this, "Something went wrong", Toast.LENGTH_SHORT).show(); 
            } 
        } 
    }); 
} 

2. 登录成功后无数据库写入逻辑

如果是已有账号登录,你的signIn方法里完全没有写入数据库的代码。如果需要在登录时也同步用户信息到数据库,记得在task.isSuccessful()的分支里添加类似注册时的数据库写入逻辑。

3. 数据库写入未添加状态监听

之前的代码调用setValue(true)后没有监听结果,就算写入失败你也看不到任何日志。一定要加上addOnSuccessListener和addOnFailureListener,这样能在Logcat里直接看到具体的失败原因,比如权限问题、网络波动、URL错误等。

4. 依赖版本不一致(潜在隐患)

你的Firebase依赖版本不统一:firebase-core:15.0.2、firebase-database:15.0.0、firebase-auth:15.1.0。虽然这不一定直接导致写入失败,但版本不一致很容易引发各种奇怪的兼容性问题,建议把所有Firebase相关依赖升级到同一稳定版本。

额外排查建议

  • 确认Firebase实时数据库的URL是否正确:如果你的数据库不在默认区域,需要在初始化时指定URL,比如FirebaseDatabase.getInstance("https://your-db-url.firebaseio.com/")
  • 检查设备网络状态,Firebase写入必须依赖网络连接
  • 打开Logcat,过滤FirebaseDatabase标签,查看有没有隐藏的错误日志

内容的提问来源于stack exchange,提问作者Roel Toca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:31:23