Reputation: 300
So I have a database in this format:
I need to be able to get the name
, price
and quantity
after I search the database for the barcode.
I tried something like this:
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("ProductData");
UserId = mFirebaseDatabase.push().getKey();
public void searchProduct(String barcode){
mFirebaseDatabase.child("Products").child("barcode").equalTo(barcode).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Log.d("DBVAL", String.valueOf(dataSnapshot.getValue()));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Here is the output:
D/DBVAL: null
Upvotes: 2
Views: 367
Reputation: 138824
You are getting that result because you aren't using the correct query. Besides that, there is no node in your database named DataUsers
. To get all children that contains a particular barcode, please use the following query:
Query barcodeQuery = mFirebaseDatabase.child("ProductData").child("Products")
.orderByChild("barcode").equalTo(barcode);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
int price = ds.child("price").getValue(Integer.class);
int quantity = ds.child("quantity").getValue(Integer.class);
Log.d("TAG", name + "/" + price + "/" + quantity);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
barcodeQuery.addValueEventListener(valueEventListener);
See, I have added in this query both nodes ProductData
and Products
, and then I order all children by barcode
property and used .equalTo(barcode)
.
Upvotes: 2