1

What is the difference between

FirebaseDatabase.getInstance().getReference()
            .child("Users")
            .child("Accounts")
            .child("AC123");

and

FirebaseDatabase.getInstance().getReference()
            .child("Users")
            .child("Accounts")
            .orderByKey()
            .equalTo("AC123");

using addListenerForSingleValueEvent seems to return the same DataSnapshot in that the toString() values are the same and using DataSnapshot.getValue() seems to return identical HashMaps but only the first reference reports that it "has children".

Trying to query for children in the second reference just throws a NPE.

{
  "Users" : {
  "Accounts" : {
    "AC123" : {
      "linked" : true,
      "sort" : 0,
      "type" : 1
    }
  },   
etc
2
  • Please edit your question to include the JSON (as text, no screenshot) that you're accessing. Also: if you have code that throws an NPE, share the minimal code that reproduces that exception. The above snippets won't. Commented Dec 9, 2016 at 12:40
  • I don't need help with the NPE as I already know it is caused by the DataSnapshot having no children but I have added a Json sample. This is a very general question. I just didn't understand why the snapshots returned by these references behave differently when they return the same node and seem to be identical. Commented Dec 9, 2016 at 13:54

1 Answer 1

2

The two queries don't return the same node.

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

This means that the second query returns a subset of the nodes under /Users/Accounts. To access the individual matched nodes, you will need to loop over snapshot.getChildren(), even when there's only a single matching child.

The first query always returns a single node, the one at /Users/Accounts/AC123. So the child's data is immediately available under snapshot.getValue().

Sign up to request clarification or add additional context in comments.

2 Comments

I see. so for the first reference, dataSnapshot.child("type").getValue() correctly returns 1 but for the second reference, I would have to de-serialize and check the hashmap in order to find the value? Am I understanding that correctly?
Nope, you have to loop over the snapshot.getChildren(). Also see the sample in the documentation on filtering data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.