从firebase示例中,我需要确定是否存在年龄= 25的恐龙,可以按照以下步骤进行操作。但是说,如果没有那个年龄的恐龙,我怎么能知道查询已经完成,并且有0个年龄= 25的恐龙。因为我的Android UI依赖于此,请继续执行下一步。
Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
Query queryRef = ref.orderByChild("height").equalTo(25);
queryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
System.out.println(snapshot.getKey());
}
// ....
});
编辑
提供的一些解决方案建议使用ValueEventListener。但是问题是即使您使用valueEventListener,在上述情况下,它仍然无效,因为有0行。 onDataChange不会触发。
Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
Query queryRef = ref.orderByChild("height").equalTo(25);
queryRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChanged(DataSnapshot snapshot) {
System.out.println(snapshot.getKey());
}
// ....
});
回答
@Override
public void onDataChange(DataSnapshot snapshot) {
//DinosaurFacts facts = snapshot.getValue(DinosaurFacts.class);
//Log.d("hz-dino", facts.toString());
if(snapshot.getValue() != null)
{
Log.d("hz-dino", snapshot.getKey());
Log.d("hz-dino", String.valueOf(snapshot.getValue()));
}
else
{
Log.d("hz-dino", "there are exactly 0 rows!");
}
}
最佳答案
要测试数据:
snapshot.getValue() != null
使用时
ref.addValueEventListener
如果该位置不存在任何数据,则快照将返回null。
关于android - 我怎么知道查询在Firebase中返回了0行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33085659/