实现用户注册时将注册页面数据同步写入Firebase数据库
Got it, let's walk through how to implement both Firebase Authentication and saving user details to the Realtime Database for your Signup activity. Here's a complete, working solution based on your code snippet:
Step 1: Complete Variable Initialization
First, finish initializing all your UI elements and Firebase instances in the onCreate method:
public class Signup extends AppCompatActivity { EditText name, mobile_no, mail, passwd, cnfpasswd; Button signup; TextView login_up; FirebaseAuth user; DatabaseReference userdetails; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); // Link UI elements to their respective IDs name = findViewById(R.id.username); mobile_no = findViewById(R.id.mobile_no); mail = findViewById(R.id.email_addr); passwd = findViewById(R.id.password); // Replace with your actual password EditText ID cnfpasswd = findViewById(R.id.confirm_password); // Replace with your actual confirm password ID signup = findViewById(R.id.btn_signup); // Replace with your actual signup button ID login_up = findViewById(R.id.tv_login); // Replace with your actual login text view ID // Initialize Firebase Auth and Database reference user = FirebaseAuth.getInstance(); userdetails = FirebaseDatabase.getInstance().getReference("Users"); // "Users" is the root node for storing user data } }
Next, add a click listener to your signup button to handle input validation, user authentication, and data storage:
@Override protected void onCreate(Bundle savedInstanceState) { // ... (previous initialization code) signup.setOnClickListener(v -> { // Get input values and trim whitespace String userName = name.getText().toString().trim(); String mobile = mobile_no.getText().toString().trim(); String email = mail.getText().toString().trim(); String password = passwd.getText().toString().trim(); String confirmPassword = cnfpasswd.getText().toString().trim(); // Basic input validation if (userName.isEmpty()) { name.setError("Name is required"); name.requestFocus(); return; } if (mobile.isEmpty() || mobile.length() != 10) { // Adjust mobile length based on your region mobile_no.setError("Enter a valid mobile number"); mobile_no.requestFocus(); return; } if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) { mail.setError("Enter a valid email address"); mail.requestFocus(); return; } if (password.isEmpty() || password.length() < 6) { passwd.setError("Password must be at least 6 characters"); passwd.requestFocus(); return; } if (!password.equals(confirmPassword)) { cnfpasswd.setError("Passwords do not match"); cnfpasswd.requestFocus(); return; } // Create user with Firebase Email/Password Authentication user.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(task -> { if (task.isSuccessful()) { // Get the unique ID of the newly created user String userId = user.getCurrentUser().getUid(); // Create a User object to store user details User userObj = new User(userName, mobile, email); // Save user details to Firebase Realtime Database userdetails.child(userId).setValue(userObj) .addOnCompleteListener(dbTask -> { if (dbTask.isSuccessful()) { Toast.makeText(Signup.this, "Registration successful!", Toast.LENGTH_SHORT).show(); // Redirect to login or home activity after successful signup startActivity(new Intent(Signup.this, LoginActivity.class)); finish(); // Close the signup activity } else { Toast.makeText(Signup.this, "Failed to save user details: " + dbTask.getException().getMessage(), Toast.LENGTH_SHORT).show(); } }); } else { // Handle authentication errors (e.g., email already in use, weak password) Toast.makeText(Signup.this, "Registration failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } }); }); // Optional: Redirect to login activity when "Already have an account?" text is clicked login_up.setOnClickListener(v -> { startActivity(new Intent(Signup.this, LoginActivity.class)); finish(); }); }
Step 3: Create a User Model Class
You need a simple model class to serialize user data into the Firebase Database. Create a new User.java file:
public class User { // Public fields are required for Firebase serialization public String name; public String mobile; public String email; // Default empty constructor (required by Firebase) public User() {} // Parameterized constructor to initialize user details public User(String name, String mobile, String email) { this.name = name; this.mobile = mobile; this.email = email; } }
Important Notes
- Ensure you've properly set up Firebase in your Android project (including adding the
google-services.jsonfile and updating yourbuild.gradledependencies) - Enable Email/Password authentication in the Firebase Console under Authentication > Sign-in method
- For testing, you can use open database rules (
{ "rules": { ".read": true, ".write": true } }), but in production, restrict access to only authenticated users with rules like:{ "rules": { "Users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } }
内容的提问来源于stack exchange,提问作者Raj K
相关产品推荐
相关产品推荐

