Android注册页面点击按钮不跳转登录页,Firebase认证异常求助
问题分析与修复方案
核心问题1:重复调用用户创建接口
你的validateUserInput方法的else分支中,再次调用了writeAccountDataToFirebase,而按钮点击事件里已经在验证通过后调用了该方法。这会导致:
- 第一次调用
createUserWithEmailAndPassword成功创建用户 - 第二次调用时,因为邮箱已存在,触发失败回调,弹出“认证失败”的提示
- 第二次调用的数据库写入逻辑不会执行,导致跳转逻辑不触发
核心问题2:User构造函数参数顺序错误
创建User对象时,参数顺序和构造函数定义不匹配:
- 构造函数定义:
User(String email, String memberId, String password, String telephone, int age) - 实际调用:
new User(email, password, memberId, telephone, age)
这会导致memberId和password字段值颠倒,数据库存储的数据错误。
其他潜在问题
validateUserInput未校验memberId和telephone是否为空,可能导致数据库写入空值- 使用
assert user != null可能在极端情况(如Auth成功但用户对象为空)导致崩溃,建议用非空判断替代
修复后的完整代码
package com.example.libmgt; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class activity_registration extends AppCompatActivity { private EditText emailInput, memberId, password, telephone, age; private Button registerButton; private FirebaseDatabase database; private FirebaseAuth mAuth; public static class User { public String email, memberId, telephone, password; public int age; public User() { // Required empty constructor } public User(String email, String memberId, String password, String telephone, int age) { this.email = email; this.memberId = memberId; this.telephone = telephone; this.password = password; this.age = age; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); emailInput = findViewById(R.id.emailInput); registerButton = findViewById(R.id.register_button); memberId = findViewById(R.id.member_id); password = findViewById(R.id.passwordInput); telephone = findViewById(R.id.telephone); age = findViewById(R.id.age); database = FirebaseDatabase.getInstance(); mAuth = FirebaseAuth.getInstance(); registerButton.setOnClickListener(v -> { String email = emailInput.getText().toString().trim(); String memberIdValue = memberId.getText().toString().trim(); String passwordValue = password.getText().toString().trim(); String telephoneValue = telephone.getText().toString().trim(); String ageValue = age.getText().toString().trim(); if (validateUserInput(email, memberIdValue, passwordValue, telephoneValue, ageValue)) { writeAccountDataToFirebase(email, memberIdValue, passwordValue, telephoneValue, Integer.parseInt(ageValue)); } }); } private boolean validateUserInput(String email, String memberId, String password, String telephone, String age) { if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) { emailInput.setError("Invalid email"); return false; } if (password == null || password.length() < 6) { this.password.setError("Invalid password"); return false; } if (age.isEmpty() || !age.matches("\\d+")) { this.age.setError("Invalid age"); return false; } if (Integer.parseInt(age) < 18) { this.age.setError("Age must be at least 18"); return false; } if (memberId.isEmpty()) { this.memberId.setError("Member ID cannot be empty"); return false; } if (telephone.isEmpty()) { this.telephone.setError("Telephone cannot be empty"); return false; } // 移除else分支的重复调用 return true; } private void writeAccountDataToFirebase(String email, String memberId, String password, String telephone, int age) { Log.d("Registration", "writeAccountDataToFirebase() called"); mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, task -> { if (task.isSuccessful()) { Log.d("Registration", "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); if (user == null) { Toast.makeText(activity_registration.this, "Failed to get user info", Toast.LENGTH_SHORT).show(); return; } DatabaseReference userRef = database.getReference("users"); // 修正构造函数参数顺序 User userData = new User(email, memberId, password, telephone, age); userRef.child(user.getUid()).setValue(userData, (error, ref) -> { if (error == null) { Toast.makeText(activity_registration.this, "Account created successfully!", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(() -> { startActivity(new Intent(activity_registration.this, activity_login.class)); finish(); }, 1000); } else { Toast.makeText(activity_registration.this, "Registration failed: " + error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } else { Log.w("Registration", "createUserWithEmail:failure", task.getException()); Toast.makeText(activity_registration.this, "Authentication failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } }); } }
额外建议
- 不要存储明文密码:Firebase Auth已经存储了用户凭证,数据库中不需要再存储明文密码,这是严重的安全隐患,建议从User类和数据库写入逻辑中移除password字段
- 优化错误提示:在失败回调中显示具体的错误信息(如
task.getException().getMessage()),方便排查问题 - 权限检查:确保Firebase Database的规则允许认证用户写入自己的数据,比如:
{ "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } }
内容的提问来源于stack exchange,提问作者Bwambalefrankline Gift
相关产品推荐
相关产品推荐

