我在 Firebase 数据库中获取了用户,但单击注册后似乎没有打开登录活动。它不停地显示进度条...
这是 registerUser 代码块
private void registerUser(String txtFullname, String txtEmail, String txtDob, String txtGender, String txtMobile, String txtPwd) {
FirebaseAuth auth = FirebaseAuth.getInstance();
Toast.makeText(this, "TESTING", Toast.LENGTH_SHORT).show();
System.out.println("TESTING");
// Create the user with email and password
auth.createUserWithEmailAndPassword(txtEmail, txtPwd).addOnCompleteListener(RegisterActivity.this,
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
System.out.println("User registration successful");
FirebaseUser firebaseUser = auth.getCurrentUser();
// Update display name of the user
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder()
.setDisplayName(txtFullname).build();
firebaseUser.updateProfile(profileChangeRequest);
// Enter user data into the Firebase real-time database
ReadWriteUserDetails writeUserDetails = new ReadWriteUserDetails(txtDob, txtGender, txtMobile);
DatabaseReference referenceProfile = FirebaseDatabase.getInstance().getReference("Registered Users");
referenceProfile.child(firebaseUser.getUid()).setValue(writeUserDetails).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
System.out.println("User data saved successfully in database");
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "User registered successfully. Please verify your email.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
System.out.println("Failed to send verification email");
Toast.makeText(RegisterActivity.this, "Failed to send verification email.", Toast.LENGTH_SHORT).show();
}
}
});
} else {
System.out.println("Failed to save user data in database");
Toast.makeText(RegisterActivity.this, "Failed to save user data.", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
});
} else {
try {
throw task.getException();
} catch (FirebaseAuthWeakPasswordException e) {
etRegPwd.setError("Password must contain 6 or more characters. Letters, numbers, and special character required");
etRegPwd.requestFocus();
} catch (FirebaseAuthInvalidCredentialsException e) {
etRegEmail.setError("Your email is invalid or already in use.");
etRegEmail.requestFocus();
} catch (FirebaseAuthUserCollisionException e) {
etRegEmail.setError("User is already registered.");
etRegEmail.requestFocus();
} catch (Exception e) {
System.out.println(e.getMessage());
Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
});
}
这是代码的输出
这是整个 RegisterActivity.java 类
package com.example.goalhero;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseAuthWeakPasswordException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Calendar;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegisterActivity extends AppCompatActivity {
EditText etRegFullname, etRegEmail, etRegDob, etRegMobile,
etRegPwd, etRegConfirmPwd;
ProgressBar progressBar;
RadioGroup rgRegGender;
RadioButton rbRegGenderSelected;
DatePickerDialog picker;
private static final String TAG = "RegisterActivity.";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
setSupportActionBar(findViewById(R.id.toolbar));
Toast.makeText(RegisterActivity.this, "You may register now.", Toast.LENGTH_LONG).show();
progressBar = findViewById(R.id.progress_bar);
etRegPwd = findViewById(R.id.et_register_password);
etRegConfirmPwd = findViewById(R.id.et_confirm_password);
etRegFullname = findViewById(R.id.et_register_fullname);
etRegEmail = findViewById(R.id.et_register_email);
etRegDob = findViewById(R.id.et_register_dob);
etRegMobile = findViewById(R.id.et_register_mobile);
rgRegGender = findViewById(R.id.radio_group_register_gender);
rgRegGender.clearCheck();
//Setting up the date picker
etRegDob.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
//date picker dialog
picker = new DatePickerDialog(RegisterActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
etRegDob.setText(day + "/" + (month + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
Button registerBtn = findViewById(R.id.registerBtn);
registerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int selectedGenderId = rgRegGender.getCheckedRadioButtonId();
rbRegGenderSelected = findViewById(selectedGenderId);
//Obatins the entered data
String txtFullname = etRegFullname.getText().toString();
String txtEmail = etRegEmail.getText().toString();
String txtDob = etRegDob.getText().toString();
String txtMobile = etRegMobile.getText().toString();
String txtPwd = etRegPwd.getText().toString();
String txtConfirmPwd = etRegConfirmPwd.getText().toString();
String txtGender;
//Validate the mobile number using matcher and pattern (regular express)
String mobileRegex = "^(\\+\\d{1,2}\\s?)?\\(?\\d{3}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}$";
Matcher mobileMatcher;
Pattern mobilePattern = Pattern.compile(mobileRegex);
mobileMatcher = mobilePattern.matcher(txtMobile);
if (TextUtils.isEmpty(txtFullname)) {
Toast.makeText(RegisterActivity.this, "Please enter your full name.", Toast.LENGTH_SHORT).show();
etRegFullname.setError("Full name is required.");
etRegFullname.requestFocus();
} else if (TextUtils.isEmpty(txtEmail)) {
Toast.makeText(RegisterActivity.this, "Please enter a valid email.", Toast.LENGTH_SHORT).show();
etRegEmail.setError("Email is required.");
etRegEmail.requestFocus();
} else if (!Patterns.EMAIL_ADDRESS.matcher(txtEmail).matches()) {
Toast.makeText(RegisterActivity.this, "Please re-enter your email.", Toast.LENGTH_SHORT).show();
etRegEmail.setError("Valid email address required.");
etRegEmail.requestFocus();
} else if (TextUtils.isEmpty(txtDob)) {
Toast.makeText(RegisterActivity.this, "Please enter your DOB.", Toast.LENGTH_SHORT).show();
etRegDob.setError("DOB required.");
etRegDob.requestFocus();
} else if (rgRegGender.getCheckedRadioButtonId() == -1) {
Toast.makeText(RegisterActivity.this, "Please select your gender.", Toast.LENGTH_SHORT).show();
rbRegGenderSelected.setError("Gender selection required.");
rbRegGenderSelected.requestFocus();
} else if (TextUtils.isEmpty(txtMobile)) {
Toast.makeText(RegisterActivity.this, "Please enter your 10-digit mobile number.", Toast.LENGTH_SHORT).show();
etRegMobile.setError("Phone number isn't valid.");
etRegMobile.requestFocus();
} else if (txtMobile.length() != 10) {
Toast.makeText(RegisterActivity.this, "Phone number must be 10-digits", Toast.LENGTH_SHORT).show();
etRegMobile.setError("Phone number isn't 10-digits.");
etRegMobile.requestFocus();
} else if (!mobileMatcher.find()) {
etRegMobile.setError("This is not a valid phone number.");
etRegMobile.requestFocus();
} else if (TextUtils.isEmpty(txtPwd)) {
Toast.makeText(RegisterActivity.this, "You must enter a password.", Toast.LENGTH_SHORT).show();
etRegPwd.setError("No password entered.");
etRegPwd.requestFocus();
} else if (txtPwd.length() < 6) {
Toast.makeText(RegisterActivity.this, "Password too short.", Toast.LENGTH_SHORT).show();
etRegPwd.setError("Password too short.");
etRegPwd.requestFocus();
} else if (TextUtils.isEmpty(txtConfirmPwd)) {
Toast.makeText(RegisterActivity.this, "Please confirm your password.", Toast.LENGTH_SHORT).show();
etRegConfirmPwd.setError("Password confirmation is required.");
etRegConfirmPwd.requestFocus();
} else if (!txtPwd.equals(txtConfirmPwd)) {
Toast.makeText(RegisterActivity.this, "Passwords must match.", Toast.LENGTH_SHORT).show();
etRegConfirmPwd.setError("Passwords don't match.");
etRegConfirmPwd.requestFocus();
etRegConfirmPwd.clearComposingText();
etRegPwd.clearComposingText();
} else {
txtGender = rbRegGenderSelected.getText().toString();
progressBar.setVisibility(View.VISIBLE);
registerUser(txtFullname, txtEmail, txtDob, txtGender, txtMobile, txtPwd);
}
}
});
}
//Register user based on given information...
private void registerUser(String txtFullname, String txtEmail, String txtDob, String txtGender, String txtMobile, String txtPwd) {
FirebaseAuth auth = FirebaseAuth.getInstance();
Toast.makeText(this, "TESTING", Toast.LENGTH_SHORT).show();
System.out.println("TESTING");
// Create the user with email and password
auth.createUserWithEmailAndPassword(txtEmail, txtPwd).addOnCompleteListener(RegisterActivity.this,
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
System.out.println("User registration successful");
FirebaseUser firebaseUser = auth.getCurrentUser();
// Update display name of the user
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder()
.setDisplayName(txtFullname).build();
firebaseUser.updateProfile(profileChangeRequest);
// Enter user data into the Firebase real-time database
ReadWriteUserDetails writeUserDetails = new ReadWriteUserDetails(txtDob, txtGender, txtMobile);
DatabaseReference referenceProfile = FirebaseDatabase.getInstance().getReference("Registered Users");
referenceProfile.child(firebaseUser.getUid()).setValue(writeUserDetails).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
System.out.println("User data saved successfully in database");
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "User registered successfully. Please verify your email.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
System.out.println("Failed to send verification email");
Toast.makeText(RegisterActivity.this, "Failed to send verification email.", Toast.LENGTH_SHORT).show();
}
}
});
} else {
System.out.println("Failed to save user data in database");
Toast.makeText(RegisterActivity.this, "Failed to save user data.", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
});
} else {
try {
throw task.getException();
} catch (FirebaseAuthWeakPasswordException e) {
etRegPwd.setError("Password must contain 6 or more characters. Letters, numbers, and special character required");
etRegPwd.requestFocus();
} catch (FirebaseAuthInvalidCredentialsException e) {
etRegEmail.setError("Your email is invalid or already in use.");
etRegEmail.requestFocus();
} catch (FirebaseAuthUserCollisionException e) {
etRegEmail.setError("User is already registered.");
etRegEmail.requestFocus();
} catch (Exception e) {
System.out.println(e.getMessage());
Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
});
}
}
这是我的 Gradle 文件
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
ext {
defaultApplicationId = 'com.example.goalhero'
}
android {
namespace 'com.example.goalhero'
compileSdk 34
defaultConfig {
applicationId defaultApplicationId
minSdk 23
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
testApplicationId defaultApplicationId
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
buildToolsVersion '34.0.0'
buildFeatures {
viewBinding true
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.11.0'
implementation 'com.google.firebase:firebase-auth:22.3.1'
implementation 'com.google.firebase:firebase-analytics'
implementation platform('com.google.firebase:firebase-bom:33.1.0')
implementation 'com.google.firebase:firebase-database:20.3.0'
implementation 'androidx.navigation:navigation-fragment:2.6.0'
implementation 'androidx.navigation:navigation-ui:2.6.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.github.bumptech.glide:glide:4.12.0'
implementation "androidx.lifecycle:lifecycle-runtime:2.7.0"
implementation "androidx.lifecycle:lifecycle-common-java8:2.7.0"
implementation "androidx.annotation:annotation:1.7.1"
implementation 'com.google.android.gms:play-services-auth:20.5.0'
implementation "androidx.credentials:credentials:1.2.2"
implementation "androidx.credentials:credentials-play-services-auth:1.2.2"
implementation "com.google.android.libraries.identity.googleid:googleid:1.1.0"
}
apply plugin: 'com.google.gms.google-services'
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.2.0'
classpath 'com.google.gms:google-services:4.4.1'
// classpath 'com.android.tools.build:gradle:8.2.2'
}
}
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '8.2.2' apply false
id 'com.android.library' version '8.2.2' apply false
id 'com.google.gms.google-services' version '4.4.2' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
我希望用户单击注册后,它会打开 LoginActivity 并显示“用户数据已成功保存在数据库中”消息。
首先,我强烈建议将每个功能分离为单独的函数,例如您可以执行以下操作:
这将改善代码组织、可重用性和可维护性。
此外,我建议在用户注册成功后发送验证电子邮件,以确保用户对象有效。
您可以在这里
看到反映我观点的完整示例