Java 适用于 Android 的 Firebase,我如何循环遍历一个孩子(对于每个孩子 = x 做 y)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40366717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Firebase for Android, How can I loop through a child (for each child = x do y)
提问by Rosenberg
This is what my test looks like:
这是我的测试的样子:
I won't use the fields above, it's just a dummy. But I would like to go through all the children on "users" and for each email return a:
我不会使用上面的字段,它只是一个虚拟的。但我想通过“用户”的所有孩子,并为每封电子邮件返回一个:
System.out.println(emailString);
The only way I found of listing an object is using firebaseAdapter, is there another way of doing it?
我发现列出对象的唯一方法是使用 firebaseAdapter,还有其他方法吗?
采纳答案by rubenlop88
The easiest way is with a ValueEventListener.
最简单的方法是使用 ValueEventListener。
FirebaseDatabase.getInstance().getReference().child("users")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
System.out.println(user.email);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
The User
class can be defined like this:
本User
类可以定义如下:
class User {
private String email;
private String userId;
private String username;
// getters and setters...
}
回答by Sunshinator
Let say you have a reference to the node users, you can iterate through the nodes as follows:
假设您有对节点users的引用,您可以按如下方式遍历节点:
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child : dataSnapshot.getChildren() ){
// Do magic here
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {}
});
Note that the DataSnapshot child
inside the for loop will have the UIDs as key, not users.
请注意,DataSnapshot child
for 循环内部将使用 UID 作为键,而不是users。
回答by Amol Dhanwat
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot item_snapshot:dataSnapshot.getChildren()) {
Log.d("item id ",item_snapshot.child("item_id").getValue().toString());
Log.d("item desc",item_snapshot.child("item_desc").getValue().toString());
}
}
}