У меня есть простое приложение, в которое люди могут зарегистрироваться (зарегистрироваться).
После этого я делаю две вещи:
1) Я отправляю письмо с подтверждением;
2) Я создаю информацию базы данных firebase для этого пользователя.
Я создаю два узла, как вы можете видеть на картинке.
узел "пользователи"
узел "users_settings"
И есть две проблемы:
1) Кажется, что 1 из каждых 20 учетных записей получает ошибку при создании, и эта специальная учетная запись не создает узел "users_settings", она просто создала узел "users" и только с полем full_name. Как этот на этой картинке.
нет узла "users_settings"
Я спросил двух пользователей, которые получили эту проблему и не нашли ничего, что они сделали неправильно, и я создал несколько учетных записей и не получил эту ошибку. Вот почему это довольно сложно решить.
2) Если пользователь нажимает кнопку регистрации и закрывает приложение во время его загрузки, firebase создает учетную запись, отправляет подтверждающее электронное письмо, но не создает никакой информации базы данных firebase, потому что она не попадает в эту часть кода , Есть ли способ предотвратить это?
Это код, когда человек нажимает кнопку регистрации, он просто берет поля (имя, адрес, пароль) и регистрируется в firebase.
RegisterFragment.java
/**
* When the user press the REGISTER BUTTON.
*/
private void init(){
Log.i(TAG, "init: Initializing the button click");
mRegisterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = mEmail.getText().toString();
String fullName = mFullName.getText().toString();
String password = mPassword.getText().toString();
if (stringIsNull(email) || stringIsNull(fullName) || stringIsNull(password)){
Toast.makeText(getActivity(), R.string.fillin_all_fields, Toast.LENGTH_SHORT).show();
} else {
firebaseMethods = new FirebaseMethods(getActivity());
/*
* 1) Create an intent to the same Login Screen;
* 2) Register email (Send verification email, if OK start Login Screen again and send message to verify the email).
*/
Intent intentLogin = new Intent(getActivity(), LoginActivity.class);
firebaseMethods.registerNewEmail(email, password, fullName, mProgressBar, intentLogin);
}
}
});
}
Это мой registerNewEmail Метод Firebase:
FirebaseMethods.java
/**
* Register a new user to the Firebase Authentication with his email and password.
* @param email the user's email for registering
* @param password the user's password for registering
*/
public void registerNewEmail(String email, String password, final String fullName, final ProgressBar progressBar, final Intent intent){
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.i(TAG, "createUserWithEmail:success");
final FirebaseUser user = mAuth.getCurrentUser();
if (user != null){
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Log.i(TAG, "onComplete: Successful send verification email");
Toast.makeText(mContext, mContext.getString(R.string.confirm_email_verification)
+ user.getEmail(), Toast.LENGTH_SHORT).show();
// 1) Add user's info to database;
// 2) Sign out to wait for the email verification;
// 3) Go to login activity.
addNewUser(fullName, "", "", "", "", "", false);
mContext.startActivity(intent);
} else {
Log.i(TAG, "onComplete: Failed to send verification email");
Toast.makeText(mContext, mContext.getString(R.string.failed_send_verification_email),
Toast.LENGTH_SHORT).show();
}
}
});
}
/*updateUI(user);*/
} else {
// If sign in fails, display a message to the user.
Log.i(TAG, "createUserWithEmail:failure", task.getException());
if (task.getException() != null) {
Toast.makeText(mContext, "Authentication failed." + task.getException().getMessage(),
Toast.LENGTH_LONG).show();
}
/*updateUI(null);*/
}
progressBar.setVisibility(View.GONE);
}
});
}
Это мой addNewUser метод:
FirebaseMethods.java
private void addNewUser(String fullName, String birthDate, String beltColor, String registrationNumber, String dojo, String profileImgURL, boolean verified) {
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
String userID = currentUser.getUid();
Log.i(TAG, "addNewUser: Adding new user database information: " + userID);
// Creating the user model with the information provided.
User user = new User(
dojo,
fullName,
profileImgURL,
registrationNumber,
verified);
// Adding to the database;
myRef.child(mContext.getString(R.string.dbname_users))
.child(userID)
.setValue(user);
// Creating the user_settings model with the information provided.
UserSettings user_settings = new UserSettings(
beltColor,
birthDate,
userID);
// Adding to the database
myRef.child(mContext.getString(R.string.dbname_users_settings))
.child(userID)
.setValue(user_settings);
// 1) Added the information for the user that just registered;
// 2) Sign out to wait for email verification.
mAuth.signOut();
}
}
Вы видите, что я создаю полную модель User (dojo, fullName, profileImgURL, registrationNumber, проверено) и полную модель UserSettings (beltColor, birthDate, userID).
И я сразу добавляю его в базу данных, так что я не могу видеть, как он добавляет только поле полного имени и не добавляет UserSettings.
Помогите мне, пожалуйста! Это мое первое приложение выпущено.