[英]How to get child based on value inside it, without knowing the child. in android firebase realtime database
I have a node for the pharmacies accounts and the children are the id of the pharmacies each child contain the name and the id of the pharmacy and some more info.我有一个药房帐户的节点,孩子们是药房的 ID,每个孩子都包含药房的名称和 ID 以及更多信息。 Now I have the pharmacy name and want to get the pharmacy ID is there any function that can do this?
现在我有了药房名称并想获得药房 ID 是否有任何 function 可以做到这一点?
What you're looking for is a database query, which allows you to filter the results under a node based on a property value.您正在寻找的是数据库查询,它允许您根据属性值过滤节点下的结果。
In this case that'd be something like this:在这种情况下,这将是这样的:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Pharmacies");
Query query = ref.orderByChild("PharmacyName").equalTo("El Ezaby");
query.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else {
DataSnapshot result = task.getResult();
for (DataSnapshot snapshot: result.getChildren()) {
Log.i("firebase", snapshot.child("PharmacyID").getValue(String.class));
}
}
}
});
The loop over result.getChildren()
is needed since a query can have multiple results.由于查询可以有多个结果,因此需要对
result.getChildren()
进行循环。 Even though it may have only one result here, you'll still need the loop.即使这里可能只有一个结果,您仍然需要循环。
DatabaseReference databaseReference1=FirebaseDatabase.getInstance().getReference("Pharmacies");
databaseReference1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot:snapshot.getChildren()){
Pharmacies pharmacies=dataSnapshot.getValue(Pharmacies.class);
if(pharmacies!=null){
if(pharmacyName.contains(pharmacies.getPharmacyName())){
Log.e("firebase", dataSnapshot.child("PharmacyID").getValue(String.class));
pharmacyid=dataSnapshot.child("PharmacyID").getValue(String.class);
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.