august alsina
august alsina

Reputation: 197

Check if child exists in firebase

Android Java Firebase:

 DatabaseReference root = FirebaseDatabase.getInstance().getReference();
    DatabaseReference users = root.child("Users");
users.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                if (snapshot.childExists("name")) {
                    // run some code
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

This is my code, but childexists is not a valid working method. What is a way to check? If there is something similar can I just fix it?

Upvotes: 1

Views: 10889

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598837

Either use hasChild():

public void onDataChange(DataSnapshot snapshot) {
    if (snapshot.hasChild("name")) {
        // run some code
    }
}

Or child().exists():

public void onDataChange(DataSnapshot snapshot) {
    if (snapshot.child("name").exists()) {
        // run some code
    }
}

Upvotes: 3

Related Questions