Infinite Loop when retrieving and writing data to Firebase
I'm a beginner on Android and had a problem retrieving a Firebase data and recording again, I know the reason for the infinite loop but I don't 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 happens that whenever the value is changed, it goes back to the method, so when the person votes, it stays in an infinite loop.. How can I fix, or use another function so that I can retrieve the current score in 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 as true and allows the user to vote again...
1 answers
This happens because you are using a ValueEventListener
. It is called whenever a change happens in the Database. This means that whenever you increment the number of votes, it is called again and increments one more time.
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) {
}
});