我想获取productQuantity
值并更新它:
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新值上不起作用。
答案 0 :(得分:1)
让我们举个例子。假设我们要获得将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);