Reputation: 4277
I'd like to create a users database in Cloud Firestore, with the email as the unique ID for each user. The users should be in a collection
, and each user is a document
.
This is how I check if the user exists in the login activity:
FirebaseFirestore db = FirebaseFirestore.getInstance();
final DocumentReference userRef = db.collection("users").document(email);
userRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
Toast.makeText(LoginActivity.this, task.getResult().toString(),
Toast.LENGTH_SHORT).show();
if (document != null) {
//The user exists...
}
else {
//The user doesn't exist...
}
}
}
else
connectionErrorActivity();
}
});
The database is empty, as you can see:
My problem is, that document
is never null, even tough the database is empty. The toast
shows that the string value of document
is: COM.GOOGLE.FIREBASE.FIRESTORE.DOCUMENTSNAPSHOT@8ED6B96
.
Is this the correct way to do this? What can I do to fix it?
Upvotes: 2
Views: 7487
Reputation: 891
Task result has a field named AdditionalUserInfo, you can find here isNewUser. it will return false if the user already exists.
if (task.result?.additionalUserInfo!!.isNewUser){
addNewUser()
} else {
updateUser()
}
Upvotes: 2
Reputation: 7870
The result of this Task
is a DocumentSnapshot
. Whether or not the underlying document actually exists is available via the exists
method.
If the document does exist you can call getData
to get at the contents of it.
Upvotes: 6