Reputation: 33
Pleas help, I have a problem when I want to add user point data from a Firebase database
I want to add the previous user's point to the newly obtained point. This is the code that I use
final DatabaseReference userDataRef = FirebaseDatabase.getInstance().getReference().child("Users").child(userRefEmail);
userDataRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String userCurrentPoint = dataSnapshot.child("point").getValue().toString();
if (userCurrentPoint != null) {
int finalPoint = Integer.parseInt(userCurrentPoint) + poin;
userDataRef.child("point").setValue(String.valueOf(finalPoint));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
But when I use it, there is an infinite continuous addition of points to the firebase database, how do I deal with this?
Upvotes: 1
Views: 349
Reputation: 80914
Use SingleValueEvent
instead of ValueEventListener
, with SingleValueEvent
it will only be called once:
userDataRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String userCurrentPoint = dataSnapshot.child("point").getValue().toString();
if (userCurrentPoint != null) {
int finalPoint = Integer.parseInt(userCurrentPoint) + poin;
userDataRef.child("point").setValue(String.valueOf(finalPoint));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Upvotes: 2