user3649775 user3649775 - 2 months ago 24
Java Question

Firebase retrieve Data from child by key

I have my database structure like below in the snapshot

Now what I am trying to do is to get all the children having

category
value of
shop


I have tried this code

Firebase ref = new Firebase("https://top-africa.firebaseio.com/businesses/);
ref.orderByChild("category").equalTo("shop");
ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Object ob = dataSnapshot.getValue();
System.out.println("There are " + dataSnapshot.getKey() + " blog posts==" + dataSnapshot.getValue());
}
});


but when I look at the log it printed out all 10 children whereas I suppose I would retrieve only one because there was only one value for
category
shop
.

I don't know what I am missing. Could you please help me to solve the issue?

Answer

your reference is pointing to bussiness, so use query to fetch the data with condition

Query mQuery = ref.orderByChild("category").equalTo("Shop");
mQuery.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot,  String s) {
                Object ob = dataSnapshot.getValue();
                System.out.println("There are " + dataSnapshot.getKey() + " blog posts==" + dataSnapshot.getValue());
            }
 });
Comments