`dataSnapShot.getChildren()` 返回 null。

huangapple go评论78阅读模式
英文:

dataSnapShot.getChildren() returning null

问题

我正在尝试使用查询来获取特定用户的用户详细信息

DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
        .child("user_account_settings")
        .orderByChild("user_id")
        .equalTo(getItem(position).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Log.d(TAG, "onDataChange: 获取的用户ID为 " + getItem(position).getUser_id());
        for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
            //做一些操作
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

[Firebase数据库截图][1]

根据数据库中获取的用户ID是正确的,并且它明显具有子节点,但由于某种原因 dataSnapshot.getChildren() 为空,因此无法允许我遍历 foreach 循环。


<details>
<summary>英文:</summary>

I&#39;m trying to fetch the user details of a particular user using a query: 

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
        Query query = reference
                .child(&quot;user_account_settings&quot;))
                .orderByChild(&quot;user_id&quot;)
                .equalTo(getItem(position).getUser_id());
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d(TAG, &quot;onDataChange: the fetched user id is &quot; + getItem(position).getUser_id());
                for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
                    //do stuff
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


    
 
[Firebase database screenshot][1]    

The user id that is fetched is correct according to the database and it clearly has children, but for some reason `dataSnapshot.getChildren()` is empty thus not allowing me to iterate through the foreach loop. 


  [1]: https://i.stack.imgur.com/ydKR9.jpg

</details>


# 答案1
**得分**: 2

你代码中的问题在于数据库中的用户 ID 属性被称为 `userid`,而在你的查询中你使用的是 `user_id`,这是不正确的。你查询中的字段名称必须与数据库中的字段名称匹配。要解决这个问题,只需将:

    .orderByChild("user_id")

改为:

    .orderByChild("userid")

<details>
<summary>英文:</summary>

The problem in your code lies in the fact that the user ID property is called in the database `userid`, while in your query you are using `user_id`, which is incorrect. The name of the field in your query must match the name field in the database. To solve this, simply change:

    .orderByChild(&quot;user_id&quot;)

To:

    .orderByChild(&quot;userid&quot;)

</details>



huangapple
  • 本文由 发表于 2020年9月14日 22:59:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63886894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定