java - 从Firebase Android读取值并更新它-LMLPHP

我想获取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新值都无效。

最佳答案

让我们举个例子。假设我们要获得将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);

10-06 10:54