Infinite loop while recovering and recording data in Firebase

Asked

Viewed 136 times

0

I’m a beginner on Android and had a problem recovering data from Firebase and record again, I know the reason for the infinite loop but I don’t know how to fix.

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 happens that whenever the value is changed, it goes back to the method, so when the person votes, it gets in an infinite loop.. How can I fix, or use another function so I can recover the current firebase score and record the data by adding +1 without the loop ? I tried to create a flag, it worked, however when the app is closed and open, the flag returns as true and allows the user to vote again...

1 answer

3


This is because you are using a 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 once more.

To solve 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) {

    }
});

Browser other questions tagged

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