如何正确解析Firebase数据快照值?

时间:2021-10-25 08:36:28

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:

我必须接收一个用户名,它的全名等于“Bobby”。因此,我尝试使用以下语法从Firebase数据库获取数据:

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

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

我从dataSnapshot.getValue()得到的是:

{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?

我想知道,如果我不知道返回的id号是什么,最好或正确的方法是什么?

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:

使用wilkas的答案,我找到了下面的代码片段来得到想要的结果:

    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'.

当几个条目的全名等于“Bobby”时,它的效果很好。

1 个解决方案

#1


1  

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").

由于您在分数下添加了监听器,您的孩子是id1、id2和id3。通过添加query . orderbychild(“fullName”). equalto(“Bobby”),您可以通过子child进行筛选,得到一个结果id3。因此,您的第一个数据快照是指一个孩子id3(尽管可能会有更多的孩子,如果他们有相同的名字“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):

因为您知道每个idX都包含这些子元素:username、score、fullName。您可以很容易地提取用户名(在您的案例中,snap是对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:

此外,您还可以检索id,如下所示:

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();

#1


1  

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").

由于您在分数下添加了监听器,您的孩子是id1、id2和id3。通过添加query . orderbychild(“fullName”). equalto(“Bobby”),您可以通过子child进行筛选,得到一个结果id3。因此,您的第一个数据快照是指一个孩子id3(尽管可能会有更多的孩子,如果他们有相同的名字“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):

因为您知道每个idX都包含这些子元素:username、score、fullName。您可以很容易地提取用户名(在您的案例中,snap是对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:

此外,您还可以检索id,如下所示:

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();