简体   繁体   中英

Firebase getting value returns NULL value

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

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM