How to fix Android Cloud Firestore document snapshot

Tags: , , ,



I am checking if the user has made an appointment in the database if not add the user(add a new document which has the user details). The problem with my app is that it runs both AddUser() and AlertUser() functions:

 DocumentReference docRef = firebaseFirestore.collection(group).document(userIdentity);
    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()){
                DocumentSnapshot documentSnapshot = task.getResult();

                if (documentSnapshot != null) {
                    if (!documentSnapshot.exists()){
                        //User does not exist create the new user

                        addUser();
                    } else {
                        //User has already made an appointment show dialog

                        AlertUser();
                    }
                }
            }else {
                Log.i("Key","Task not successfull");
            }
        }
    });

Answer

What does this code do is checking whether a document with the userIdentity id actually exists. If it doesn’t exist, the addUser() method is called, otherwise, the AlertUser() is called. There is no way in which both parts of the if statement are evaluated. So it’s one or the other. You can have both method calls only if you access all those lines of code twice. Meaning that the first time the user is created and the second time is alerted. To solve this, remove from your code the part where you are calling the above code twice.

This is a Cloud Firestore question and not a Firebase Realtime database one, so I’ve changed the tag accordingly.



Source: stackoverflow