-2
I want to recover the value of a drive in Firebase and save that value whenever the field flag
for "noDebitado"
and thereafter, with each loop interaction for
, I want to set a new value for flag
inside the Firebase to "debitado"
.
By doing so I can get the value of each drive:
public void pegarValorMov(){
String emailUsuario = autenticacao.getCurrentUser().getEmail();
String idUsuario = Base64Custon.codificarBase64(emailUsuario);
movimentacaoRef = firebaseRef.child("movimentacao").child( idUsuario).child( mesAnoSelecionado );
valueEventListenerMov = movimentacaoRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot dados : snapshot.getChildren()) {
Movimentacao movimentacao = dados.getValue(Movimentacao.class);
//retornando o nó principal de cada movimentacao
key = dados.getKey();
if (movimentacao.getFlag().equals("noDebitado")) {
//recupera o valor da movimentaçao
valorReceita = movimentacao.getValor();
//exibe o valor da movimentacao atual
Log.i("VALOR", "Valor Receita " + valorReceita );
//soma o valor da movimentação a cada interaçao
vReceita = vReceita + valorReceita;
}
}//fim do for
//exibe o valor total das movimentacoes encontradas para futuros calculos
Log.i("VALOR", "Valor Receita total " + vReceita );
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
I wish to change the value of flag
whenever she is equal to "noDebitado"
, I tried to do this by adding the following line of code inside the block if
.
if (movimentacao.getFlag().equals("noDebitado")) {
//recupera o valor da movimentaçao
valorReceita = movimentacao.getValor();
//exibe o valor da movimentacao atual
Log.i("VALOR", "Valor Receita " + valorReceita );
//soma o valor da movimentação a cada interaçao
vReceita = vReceita + valorReceita;
//trecho que alterar o valor da flag no firebase
movimentacaoRef.child(key).child("flag").setValue("debitado");
}
It worked, the value of flag
in Firebase was changed, but it emits a slightly strange result (image below), so the value of each drive repeated, as if the loop for
run more times than the amount of items in Firebase.
... found some issues about the onDataChange
run more than once when a data is changed in Firebase, but got a little confused.
Thank you for contributing Paul, your help helped me to find the solution. Actually when the "flag" was changed onDataChange was triggered again, thus generating "loop" (callback). And actually change the value of the "flag" directly , like this: moverRef.Child(key). Child("flag"). setValue("debited"); is not very suitable, so I created an update method within the class to be triggered when desired. Vlw, hug.
– Giovane