pawliux
pawliux

Reputation: 193

How to parse Firebase DataSnapshot value correctly

I have to receive a username that has a fullName equal to "Bobby". So I'm trying to get data from Firebase Database using the following syntax:

ref.orderByChild("fullName").equalTo("Bobby").addListenerForSingleValueEvent(new ValueEventListener() {...}

What I get from dataSnapshot.getValue() is this:

{id3={username=bob, score=150, fullName=Bobby}}

I would like to know what is the best or correct way to get the username if I do not know which id number was returned?

Currently I'm achieving it this way:

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference("Scores");

    ref.orderByChild("fullName").equalTo("Bobby").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.i(TAG, "dataSnapshot value = "+dataSnapshot.getValue());
            if(dataSnapshot.hasChildren()){
                Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
                DataSnapshot snap = iter.next();
                if(snap.hasChildren() && snap.getValue() instanceof HashMap) {
                    HashMap map = (HashMap) snap.getValue();
                    if(map.containsKey("username")) {
                        Log.i(TAG, "onDataChange: username = " + map.get("username"));
                    }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

EDIT: The Database structure is looking like this:

     {
      "Scores" : {
        "id1" : {
          "fullName" : "Robert",
          "score" : 96,
          "username" : "rob"
        },
        "id2" : {
          "fullName" : "Michael",
          "score" : 87,
          "username" : "mike"
        },
        "id3" : {
          "fullName" : "Bobby",
          "score" : 150,
          "username" : "bob"
        }
      }
    }

Thanks in advance.

SUMMARY:

Using wilkas' answer I came to the following code snippet to get the wanted result:

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference("Scores");

    ref.orderByChild("fullName").equalTo("Bobby").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.i(TAG, "dataSnapshot value = "+dataSnapshot.getValue());
            if(dataSnapshot.hasChildren()){
                Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
                while (iter.hasNext()){
                    DataSnapshot snap = iter.next();
                    String nodId = snap.getKey();
                    String username = (String) snap.child("username").getValue();

                    //received results
                    Log.i(TAG, username + " on nod " + nodId);
                }

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

It works well when several entries have a fullName equal to 'Bobby'.

Upvotes: 3

Views: 4017

Answers (1)

wilkas
wilkas

Reputation: 1213

Since you add listener under Scores, your childs are id1, id2 and id3. By adding query .orderByChild("fullName").equalTo("Bobby") you filter by subchild and get one result id3. So your first datasnapshot refers to one child id3 (though there could be more children if they would have same name of "Bobby").

In order to get the username, you need to iterate each received child (as you correctly do) - in this case only one child is iterated - and then get child username of that iterated child.

Since you know that every idX contains these children: username, score, fullName. You can easily extract username as follows (in your case snap is reference to child id3):

String username = (String) snap.child("username").getValue();
String fullName = (String) snap.child("fullName").getValue();
long score = (long) snap.child("score").getValue();

Furthermore you can retrieve id too as follows:

String recordId = snap.getKey();

Within the inner iteration you could also get username as follows:

String recordId = snap.getKey();
String username = (String) dataSnapshot.child(recordId).child("username").getValue();

Upvotes: 2

Related Questions