简体   繁体   中英

Adding data from firebase causes an infinite loop

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?

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) {
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM