I'm having problems when creating users in the Authentication and Database parts of Firebase Firestore.
When users register, a new ID (UID in Authentication) will be generated, and another ID (document ID under users collection) will be generated. I'm trying to make both IDs in both the Authentication side and document ID the same when users create an account.
This is my code:
firebaseAuth.createUserWithEmailAndPassword(userEmail, userPassword)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
// Sign up success -> user data should store inside db
if (task.isSuccessful()) {
firebaseAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) { //registered successfully
user.put("email", email.getText().toString());
user.put("password", password.getText().toString());
//To write a user to the database
mDatabase.collection("users").add(user)
// successfully add to db
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(getBaseContext(), "SUCCESS: Your account was created successfully! Please check your email for verification. User "
+ email.getText().toString() + " has been added to the database.", Toast.LENGTH_LONG).show();
Intent loginActivity = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginActivity);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getBaseContext(), "Error adding to DB", Toast.LENGTH_LONG).show();
}
});
}
// task was unsuccessful
else {
String fail = "FAIL: User failed to register: " + task.getException();
Toast.makeText(getBaseContext(), fail, Toast.LENGTH_LONG).show();
Log.e("", fail);
}
}
});
}
else{
String fail = "FAIL: User failed to register: " + task.getException();
Toast.makeText(getBaseContext(), fail, Toast.LENGTH_LONG).show();
Log.e("", fail);
}
}
});`
I have tried setting the data using
FirebaseFirestore mDatabase = FirebaseFirestore.getInstance();
DocumentReference usersRef = mDatabase.collection("users").document(currentUser);
String id = firebaseAuth.getUid();
usersRef.document(id).set(user);
to replace the parts of code in
Map<String, Object> user = new HashMap<>();
user.put("name", name.getText().toString());
user.put("email", email.getText().toString());
user.put("password", password.getText().toString());
but I got errors in the .addOnSuccessListener(new OnSuccessListener<DocumentReference>()
portion of codes
I'm new to Firebase, so any help would be appreciated:)