0

I'm new to Android and stuck on the following issue-

My Firebase Database

In JSON:

{ "-LwDpiyCDf8tsjTfTF3Q" : { "productImage" : "https://firebasestorage.googleapis.com/v0/b/bookmybook-13560.appspot.com/o/bmbuploads%2F1576501910798.jpg?alt=media&token=a431aec5-0994-4acf-b597-e31b87775ac8", "productName" : "image" }, "-LwDsEXofrJaz9SAjPi4" : { "productImage" : "https://firebasestorage.googleapis.com/v0/b/bookmybook-13560.appspot.com/o/bmbuploads%2F1576502569064.jpg?alt=media&token=573bcfc0-d29e-4e8c-9076-af2868c1c7a5", "productName" : "mgj" } }

I have product name in my code and I want to fetch the image (i.e productImage in this case) by passing the product name as a WHERE condition and finally load that image into an ImageView.

I tried using following code:

Query query = databaseReference.child("bmbuploads").orderByChild("productName").equalTo("image");
query.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

I don't know if the query I have formed is correct or not. Also, even after searching a lot, I can't figure out what code to write in onDataChange() method.

Please guide me on this.

bluestorm
  • 21
  • 4

3 Answers3

0

The query is correct inside onDataChange you need to retrieve the values from the database:

Query query = databaseReference.child("bmbuploads").orderByChild("productName").equalTo("image");
query.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot ds :dataSnapshot.getChildren()) {
              String productUrl = ds.child("productImage").getValue(String.class);

            }
         } 

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

After adding a reference to node bmbuploads you need to iterate to be able to retrieve the child productImage

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
0

To get the value of productImage property, please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("bmbuploads").orderByChild("productName").equalTo("image");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String productImage = ds.child("productImage").getValue(String.class);
            Log.d(TAG, productImage);
        }
    }

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

See, even if you want to return a single result, you have to loop through the productImage object using the getChildren() method. This object should contain a list of objects. Even if it's only one result, you need to iterate.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thank you so much for your solution! After getting that Image URL stored in a string variable, how can I set it to an ImageView? – bluestorm Dec 20 '19 at 10:09
  • *there's a strange id like "-LwDsEXofrJaz9SAjPi4". So, isn't it counted as an intermediary child?* It does not since we are looping through the entire object. *how can I set it to an ImageView?* Simply inside `onDataChange` use Glide Library as explained **[here](https://stackoverflow.com/a/58589011/5246885)**. After that, tell me if it work. – Alex Mamo Dec 20 '19 at 10:20
0

1 -> get all product first try below code for that
2 -> than after you get both product and product image

==> if want to get product by query you need to store details with key in some other entity that have key of product and productname only.

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference allProducts = rootRef.child("bmbuploads");
addressRef.addListenerForSingleValueEvent(valueEventListener);
List<Products> listAllProduct = new List<Products>



ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
         Log.d(TAG, "total days count: " + dataSnapshot.getChildrenCount());
        // dataSnapshot.getChildren()  give all the days e.g day 1,day 2  // you can get your count here
          for(DataSnapshot ds : dataSnapshot.getChildren()) {
               String key = ds.getKey();  // get key as day 1 

            // add one more observer that give you days matches e.g  
            DatabaseReference childRef = rootRef.child("bmbuploads").child(key);  //where key = e.g day 1                  
            // add new listent that give you detail of address 
            childRef.addListenerForSingleValueEvent(productValueventListner);   // This value event lister give you child matches  

            /**
            * For matches add dayvalueevent listent that give you all matches count.
            **/

        }
    }

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



// give all products
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
         Log.d(TAG, "total days count: " + dataSnapshot.getChildrenCount());
        // dataSnapshot.getChildren()  give all the days e.g day 1,day 2  // you can get your count here
           Products producs = dataSnapshot.getValue(Products.class);
           listAllProduct.add(producs);  // you go all product here
           Log.d("allProducts",listAllProduct.toString());

    }

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


public static class Products {

  public String productImage;
  public String productName;


    public String getProductImage() {
        return productImage;
    }

    public void setProductImage(String productImage) {
        this.productImage = productImage;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

}
Jai Khambhayta
  • 4,198
  • 2
  • 22
  • 29