Firebase Database DataSnapshot Filter for Kids on Android
I want to request data from Firebase on Android. And this is my data
And this is my Android Studio code:
Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
myFirebaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
int size= (int) snapshot.getChildrenCount();
txtMyCoffee.setText(""+size);
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Question: The total number of children is 4. How can I filter children just to include children whose "coffeeNo" is "Acoffee"?
+3
source to share
3 answers
Just improve your query to only get the result you are looking for:
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReferenceFromUrl("https://....../myCoffee/"+phone+"");
Query acoffeeQuery = databaseRef.orderByChild("coffeeNo").equalTo("Acoffee");
acoffeeQuery.addValueEventListener(new ValueEventListener() {
Override
public void onDataChange(DataSnapshot snapshot) {
final int size = (int) snapshot.getChildrenCount();
//size is equal to 2
}
@Override
public void onCancelled(FirebaseError firebaseError) {}
});
This way you don't have to iterate over all the results, and you don't have to manually iterate over the counter.
+4
source to share
Please use the following code:
Firebase rootRef = new Firebase("https://....../myCoffee/" + phone);
rootRef.addValueEventListener(new ValueEventListener() {
Override
public void onDataChange(DataSnapshot dataSnapshot) {
int size = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String coffeeNo = ds.child("coffeeNo").getValue(String.class);
if(coffeeNo.equals("Acoffee")) {
size++;
}
}
txtMyCoffee.setText(String.valueOf(size));
}
@Override
public void onCancelled(FirebaseError firebaseError) {}
});
Edit: Another approach is to use a simple query
one like this:
Firebase rootRef = new Firebase("https://....../myCoffee/"+phone+"");
Query query = rootRef.orderByChild("coffeeNo").equalTo("Acoffee");
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int size = (int) dataSnapshot.getChildrenCount();
txtMyCoffee.setText(String.valueOf(size));
}
@Override
public void onCancelled(FirebaseError firebaseError) {}
});
In your case it txtMyCoffee
will be displayed: 2
.
+2
source to share
Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
myFirebaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
int count=0;
for(DataSnapshot item: dataSnapshot.getChildren())
{
String coffeeNo=item.child("coffeeNo").toString();
if(coffeeNo.equals("Acofee")
count+=1;
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Try something like this
+1
source to share