Home > Mobile >  Firebase: Checking whether a value already exists in any of the child nodes or not
Firebase: Checking whether a value already exists in any of the child nodes or not

Time:08-16

I want to find whether a email (entered by the user) already exists in the my Firebase child node or not.

How do i check it?

MY PROGRAM:

String email = "[email protected]";
Query check = FirebaseDatabase.getInstance().getReference("student").child(RANDOM_ID).orderByChild("email").equalTo(email);
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {

            if(snapshot.exists())
            {
                Toast.makeText(this, "Email already exists!", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this, "Email doesn't exists!", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    };
    check.addListenerForSingleValueEvent(eventListener);

note: i'm using RANDOM_ID just for the reference, it'll be randomly generated id's

Here's my Firebase database

CodePudding user response:

When you run a query on that path, Firebase checks the condition for each child directly under that path. Since you run the query on /student/$RANDOM_ID, it then checks each child node under that (so email, id, etc) whether they have a property email with the given value. And since there is no /student/$RANDOM_ID/email/email, the query doesn't match any nodes.

The correct query to check whether any direct child node of student has a email property with the given value, is:

Query check = FirebaseDatabase.getInstance().getReference("student").orderByChild("email").equalTo(email);
  • Related