Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 813
Nirmal Avatar asked Sep 20 '16 11:09

Nirmal


People also ask

How do I get particular data from Firebase?

Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.

How do I get my child in Firebase?

You can use the reference to the new data returned by the push() method to get the value of the child's auto-generated key or set data for the child. Calling getKey() on a push() reference returns the value of the auto-generated key.

What is getKey () in Firebase?

public String getKey () Returns. The key name for the source location of this snapshot or null if this snapshot points to the database root.

Does Firebase have primary key?

This chat application allows users to store the basic profile and contact list. The user profile would be located on a path such as Users/$uid. User is a node in it and will have a sort of primary key associated with an ID. So, we can access each one uniquely.


1 Answers

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());
            }
 });
like image 60
Jay Vignesh Avatar answered Sep 29 '22 19:09

Jay Vignesh