Home > other >  infinite looping when updating nodes in firebase android studio
infinite looping when updating nodes in firebase android studio

Time:05-09

Here is my code

if (v == btnAddition) {
    dbRef = FirebaseDatabase.getInstance("https://mathcc-652c5-default-rtdb.asia-southeast1.firebasedatabase.app/").getReference("Quizzes").child("1");

    System.out.println(dbRef.child("addition").get().toString());

    dbRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists()) {
                QuizList quizList = snapshot.getValue(QuizList.class);

                String addition = quizList.getAddition();

                System.out.println(quizList.getAddition());

                if (addition.equals("yes")) {
                    QuizList quizList1 = new QuizList("no"
                            , quizList.getMultiplication()
                            , quizList.getSubtraction()
                            , quizList.getDivision()
                            , quizList.getMeasurement());

                    dbRef.setValue(quizList1);
                  return;
                } else if (addition.equals("no")) {
                    QuizList quizList1 = new QuizList("yes"
                            , quizList.getMultiplication()
                            , quizList.getSubtraction()
                            , quizList.getDivision()
                            , quizList.getMeasurement());

                    dbRef.setValue(quizList1);
                    return;
                }
            } else {
                QuizList quizList = new QuizList("yes", "yes", "yes", "yes", "yes");

                dbRef.setValue(quizList);
            }
        }


        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}

it keeps looping into eternity whenever I click the button. I don't know what I'm doing wrong . Im fairly new to firebase and android please help

The data I'm trying to change in my database:

CodePudding user response:

When you call addValueEventListener on a path, your onDataChange gets called right away with the current value at the path, and it will then also get called whenever any data under the path changes.

Since you write back to the same path in your onDataChange, that triggers the listener again, which invokes your onDataChange again, which then writes to the same path again, which triggers the listener again.... etc.

If you only want to read the data once, use either get() or addListenerForSingleValueEvent:

dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
    ...
  • Related