memoryManagers memoryManagers - 4 years ago 187
Android Question

Firebase exists() vs null

Normally when I check to see if the database contains a node I do something like:

users = dbReference.getReference("users").child(someUser);


I do not use
hasChild()
because I know on a large dataset this can take sometime to query. However, recently I ran into the method
exists()
found here on documentation now I was just wondering how does this differ from me just checking if the snapshot is null? And how does the
exists()
function work? Like
hasChild()
iterates over the dataset what does
esists()
do?

And is it better than checking for null? the documentation doesn't say much

thanks

UPDATE 1

Assuming i have the following node:

example node

When a user wants to register, I check this node to see if the username is taken:

userTakenNode.addListenerForSingleValueEvent(new ValueEventListener() {


@Override
public void onDataChange(DataSnapshot dataSnapshot) {

if (!dataSnapshot.hasChild(enteredUsername)) {
register();
}

}


If the username is not taken then I register the user with that username and add the username to the node above. Now I am using hasChild() to my understanding though this will iterate over the whole node till it finds it and will return it else wont return anything. On a large dataset this can take very long.

Is there a quicker way to query the dataset?

Answer Source

You'll definitely want to only check the specific user name. So attach your listener one level lower in the tree:

userTakenNode.child(enteredUsername).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (!dataSnapshot.exists) {
            register();
        } 
    }

But in general this scenario is better suited for a transaction, which combines getting the current value of the node and setting its new value into a single operation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download