0

Good morning/day/evening, I have a problem with EventListner. It triggers the infinite amount of times for whatever reason, I can't unserstand. I'd be really greateful if someone could explain me why. Like for example if my variable 'right' = 1 and 'wrong' = 0, then the data which gets bigger bc of its sum with variable 'right' updates infinite amount of times in FireBase FireStore.

public void addResultsToDB(final int right, final int wrong) {

    final FirebaseAuth fAuth = FirebaseAuth.getInstance();

    final String userId = fAuth.getCurrentUser().getUid();

    fStore = FirebaseFirestore.getInstance();


    final DocumentReference documentReference = fStore.collection("usersData").document(userId);

    documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {




            if(fAuth.getCurrentUser()!=null) {

                int totalN = Integer.parseInt(value.getString("TotalQuestions"));
                int rightN = Integer.parseInt(value.getString("RightAnswers"));
                int wrongN = Integer.parseInt(value.getString("WrongAnswers"));

                String theNameString = value.getString("uName");
                String emailStringX = value.getString("Email");

          

                Map<String, Object> userDataX = new HashMap<>();
                userDataX.put("uName", theNameString);
                userDataX.put("Email", emailStringX);
                userDataX.put("TotalQuestions", Integer.toString(totalN+1));
                userDataX.put("RightAnswers", String.valueOf(rightN + right));
                userDataX.put("WrongAnswers", String.valueOf(wrongN + wrong));

                documentReference.set(userDataX);




            }
        }
    });

}
Nick
  • 119
  • 1
  • 1
  • 5
  • I would recommend taking a look [here](https://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks) for information on how to format your code. – Henry Twist Mar 30 '21 at 15:29
  • Simply use get(). In that case, there will no infinite loop. Keeping a listener active on a reference at which you are doing some changes, will always create that infinite loop. Get the data only one. If you need to listen for changes in real-time, don't do the changes inside the callback. – Alex Mamo Mar 30 '21 at 15:40

0 Answers0