I have a problem with retrieving and updating a value from Firebase realtime database:
reff = FirebaseDatabase.getInstance().getReference("Items").child(a);
reff.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Items items = dataSnapshot.getValue(Items.class);
Integer na = items.getItemQuantity();
if (na <= 0) {
Toast.makeText(CheckOut.this, "Out of Stock", Toast.LENGTH_LONG).show();
} else {
na--;
snap.child("itemQuantity").getRef().setValue(na);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Error log on line 60 from the if-else.
According to your last comment:
yes a is the barcode that i will receive from barcode. itemQuantity of a single child.
To get the value of itemQuantity
property of a single child, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference barcodeRef = rootRef.child("Items").child("1234567781");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long itemQuantity = dataSnapshot.child("itemQuantity").getValue(Long.class);
Log.d(TAG, String.valueOf(itemQuantity));
//Do what you need to do with itemQuantity
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
barcodeRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
14
The problem in your code is that you are looping through the dataSnapshot
object using getChildren()
method when is actually not necessary. You should only get the correct reference as in the above code and simply use the value of itemQuantity
property as needed.
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.