Check for Firebase node

Asked

Viewed 24 times

-1

Good afternoon, I am checking if there is a node in Firebase, if it exists I will just increment the value on that node, but when it does not exist I will create the node, but Else is not working. If this is the first time the user will register a monthly expense, the node month/year will not exist yet, then I need to create it, and the next times the node will already be created, then I only increase with the value that is already registered.

public void atualizarDespesaMensal(Double despesaMes, Double valorDigitado,String mesAno){

        //Recuperamos o email do usuario logado
        String emailUsuario = autenticacao.getCurrentUser().getEmail();
        //codificamos usando a classe Base64Custom
        String idUsuario = Base64Custom.codificarBase64(emailUsuario);

        movimentacaoSaldoMensalRef = firebaseRef.child("saldoMensal")
                .child(idUsuario);                    

        valueEventListenerAtualizarDespesaMensal = movimentacaoSaldoMensalRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
              

                if (snapshot.child(mesAno).exists()) {
                    Log.i("IF", "O nó existe, vamos incrementa o valor"); //IF FUNCIONA
                    
                }else{
                    Log.i("ELSE", "Se o nó não existir irei criar"); //NO ELSE NÃO FUNCIONA
                }   

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }

1 answer

0

try using firebase increment.

movimentacaoSaldoMensalRef = firebaseRef.child("saldoMensal")
    .child(idUsuario)
    .set(firebase.database.ServerValue.increment(valor))

this method increments if the node already has a value and creates if it does not exist. remember that this calculation is performed on the server. and not on the client.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.