Alex
Alex

Reputation: 77

how to break infinite loop in fire-base real-time

I have coding a code that runs for validation purpose. I have created through variables that get contents from the data they worked pretty fine but when I compare the stored data with the data that user wants to store it check and then keep store data until I close the app forcefully. below is the code

 private void checkThedatafirest() {
        AppointmentREf.child("Appointments").child(userId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()){
                    StartBusinse= mDisplayDate.getText().toString();
                    sAppoint = sTimeApp.getText().toString();
                    eAppoint = eTimeApp.getText().toString();

                    for (DataSnapshot snapshot: dataSnapshot.getChildren()){
                        String  StartTime = snapshot.child("startFirstAppoint").getValue().toString();
                       String  EndTime = snapshot.child("endSecondAppointment").getValue().toString();
                        String  Date = snapshot.child("startBusinse").getValue().toString();
                        if (!StartBusinse.equals(Date)&& !sAppoint.equals(StartTime)&&!eAppoint.equals(EndTime)){
                              sendDataTofireStore();

                            break;
                        }else {
                            Toast.makeText(AppointmentInfo.this, "The data already exist , please change ",Toast.LENGTH_SHORT).show();

                        }
                        break;
                    }
                }else {
                    sendDataTofireStore();
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

Upvotes: 0

Views: 682

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

It's hard to be certain from the code you shared, but typically this sort of behavior is caused by updating the data that you listen for. If that is the case, the flow is as follows:

  1. You attach a listener to some data
  2. Firebase reads that data and calls your onDataChange
  3. You make a change to the data, and write it to the database
  4. Firebase detects that change, and invokes your onDataChange
  5. Go back to #3

The solution is to either not write the data that you read, or to ensure the data is only listened to once. The correct solution depends on the use-case, but the simplest case for scenario 2 is definitely to use addListenerForSingleValueEvent:

AppointmentREf.child("Appointments").child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
  ...

Upvotes: 1

Related Questions