英文:
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'm trying to fetch the user details of a particular user using a query:
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: the fetched user id is " + 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("user_id")
To:
.orderByChild("userid")
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论