1
votes

I have written the following code for searching the specific node and it does work correctly.

private void SearchFirebase() {
    Rootref.orderByChild("IMG").equalTo(imUrl).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot product : snapshot.getChildren()){
                id = product.getKey(); //returns the id(for eg. 8006)
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

But I don't know how to access the child key-value pairs once the specific parent key is known Firebase snapshot

In the picture above I need to fetch the key-value pairs such as Product Name or Product Discount etc.

2

2 Answers

2
votes

You just have to add child to your reference and get data as explained in this answer

private void SearchFirebase() {
    Rootref.orderByChild("IMG").equalTo(imUrl).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot product : snapshot.getChildren()){
                id = product.getKey();
                Log.i(TAG, Rootref.child(id).child("Product Discount").getValue(String.class));
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}
1
votes

When querying a Firebase Realtime Database, the most convenient way for getting the data out is by calling the right child directly from "DataSnapshot" object and converting it to the right type, as explained in the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = rootRef.child("Products");
Query imgUrlQuery = productsRef.orderByChild("IMG").equalTo(imUrl);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String productDiscount = ds.child("Product Discount").getValue(String.class);
            String productId = ds.child("Product Id").getValue(String.class);
            String productName = ds.child("Product Name").getValue(String.class);
            String productPrice = ds.child("Product Price").getValue(String.class);
            String shopName = ds.child("Shop Name").getValue(String.class);
            Log.d("TAG", productDiscount + "/" + productId + "/" + productName + "/" + productPrice + "/" + shopName);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
};
imgUrlQuery.addListenerForSingleValueEvent(valueEventListener);

The result in the logcat will be:

0/8006/Frooti/50/shop-A