private void updateValue() {
try {
newQuantity = Integer.parseInt(editTextQuantity.getText().toString());
} catch (NumberFormatException e) {
editTextQuantity.setError("Enter Charger Quantity");
return;
}
DatabaseReference mReference = FirebaseDatabase.getInstance().getReference();
mReference.child("goods").child("charger").orderByChild("productQuantity").equalTo(quantity)
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
dataSnapshot.getRef().setValue(newQuantity);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
我使用了
addChildEventListener
,但是对数量旧值和newQuantity新值都无效。 最佳答案
让我们举个例子。假设我们要获得将productQuantity
属性设置为362
的产品,并且要将其增加10。要实现此目的,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("goods").child("charger").orderByChild("productQuantity").equalTo(362);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
int productQuantity = ds.child("productQuantity").getValue(Integer.class);
int newQuantity = productQuantity + 10;
ds.child("productQuantity").getRef().setValue(newQuantity);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);