Infinite loop when retrieving and writing data in Firebase

0

I'm new to Android and had a problem retrieving a data from Firebase and recording again, I know the reason for the infinite loop but I do not know how to fix it.

public static void setVoto (String candidato){
    votoFirebase = referenciaDatabase.child(candidato).child("votos");



    votoFirebase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            voto = dataSnapshot.getValue().toString();
                votoInt = Integer.parseInt(voto);
                votoFirebase.setValue(votoInt + 1);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

The problem is that whenever the value is changed, it returns to the method, so when the person votes, it gets in an infinite loop. How can I fix it, or use another function so I can retrieve the current score on the firebase and can write the data by adding +1 without the loop occurring? I tried to create a flag, it worked, but when the app is closed and opened, the flag returns true and allows the user to vote again ...

    
asked by anonymous 26.07.2018 / 20:28

1 answer

3

This is because you are using ValueEventListener . It is called whenever a change occurs in the Database. This means that whenever you increase the number of votes, it is called again and increments again.

To resolve this, use a ListenerForSingleValueEvent :

votoFirebase.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        voto = dataSnapshot.getValue().toString();
        votoInt = Integer.parseInt(voto);
        votoFirebase.setValue(votoInt + 1);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
    
26.07.2018 / 22:21