Josias Reis
Josias Reis

Reputation: 1

How to increment counter in a transaction in Firestore Android?

I am following an example of transactions identical to the documentation of Firebase Android.

But the code is executed many times, making the counter increment several times, but would have to increment only once.

final DocumentReference produtosRef = db.collection("Produtos").document(produtoSelecionado.getKey());

    db.runTransaction(new Transaction.Function<Void>() {
        @Override
        public Void apply(Transaction transaction) throws FirebaseFirestoreException {
            DocumentSnapshot snapshot = transaction.get(produtosRef);
            if(snapshot.exists()){
                Produto produto = snapshot.toObject(Produto.class);
                String key = snapshot.getId();
                Map<String, Object> childUpdates = new HashMap<>();
                childUpdates.put("quantidadeItensEstoque",produto.getQuantidadeItensEstoque() + compra_x_produto.getQuantidadeComprado());
                childUpdates.put("precoVenda", compra_x_produto.getPrecoVendaProduto());
                produtosRef.update(childUpdates);
                // Success
                return null;
            }else{
                // se nao tiver nenhum item ainda desse produto so faz o update
                String key = snapshot.getId();
                Map<String, Object> childUpdates = new HashMap<>();
                childUpdates.put("quantidadeItensEstoque",  compra_x_produto.getQuantidadeComprado());
                childUpdates.put("precoVenda", compra_x_produto.getPrecoVendaProduto());

                produtosRef.update(childUpdates);
                LoadingUtil.hideLoading();
                // Success
                return null;
            }
        }
    }).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "Transaction success!");
        }
    })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG, "Transaction failure.", e);
                }
            });

Upvotes: 0

Views: 1203

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 139019

There is no need to use a transaction in order to increment a counter in a Cloud Firestore database. You can increment your counter with the use of FieldValue's increment() method, which will help you incrementing values atomically:

FieldValue.increment(yourNumber);

Returns a special value that can be used with the set() or update() that tells the server to increment the field's current value by the given value.

Upvotes: 1

Related Questions