0

I have firebase database in my android project which contains three values: code, email, date. I am using switchcompat for counting present students in the firebase database. When switch will be checked, data will enter into the firebase database checking if the email is uniqe in the specific date. When switch will be unchecked, that current date's data will be removed. But my problem is that for the first time when I check the switch, it works fine. And in the second time after unchecking the switch once, when I check it once again, it enters data into firebase but also remove it automatically immediately even switch is still checked. I don't understand where is the problem in my code. I am providing my code in the below for working of SwitchCompat. Here is the code:

switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Date c = Calendar.getInstance().getTime();
            SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
            final String date = df.format(c);
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, -1);
            final String previousDate = df.format(cal.getTime());
            final int[] i = {0};
            if (switch1.isChecked()) {
                Query equery = present.orderByChild("email").equalTo(email);
                equery.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (!dataSnapshot.exists()) {
                            String code = "1";
                            PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
                            String uploadId = present.push().getKey();
                            present.child(uploadId).setValue(presentStu);
                        } else {
                            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                                String eemail = snapshot.child("email").getValue().toString();
                                String ddate = snapshot.child("date").getValue().toString();
                                if (eemail.equals(eemail) && ddate.equals(date)) {
                                    i[0]++;
                                    break;
                                }
                            }
                           // Toast.makeText(User.this,""+i[0]+"",Toast.LENGTH_SHORT).show();
                                if (i[0] < 1){
                                    String code = "1";
                                    PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
                                    String uploadId = present.push().getKey();
                                    present.child(uploadId).setValue(presentStu);
                                }
                            }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
            } else {
                Query equery = present.orderByChild("email").equalTo(email);
                equery.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                            String eemail = snapshot.child("email").getValue().toString();
                            String ddate = snapshot.child("date").getValue().toString();
                            if (eemail.equals(eemail) && ddate.equals(previousDate)) {
                                present.child(dataSnapshot.getChildren().iterator().next().getKey()).child("code").setValue("0");
                            }
                            if (eemail.equals(eemail) && ddate.equals(date)) {
                                snapshot.getRef().removeValue();
                                break;
                            }
                        }

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
            }
        }
    });

Please, help me to find out the lacking in my code.

My database structure

  • This is because you call `equery.addValueEventListener()`: this is not an one-shot event listener, but will called every time. If you switch it on, off and on again, it has 3 event listeners. Change the event listener to an ordinary query and you're good. – Michiel Nov 15 '19 at 12:09
  • Michiel, Can you suggest me ordinary query example? – Shubho Sikder Nov 15 '19 at 12:14

1 Answers1

0

Because I do not know the structure of you database, you can't simply copy/paste this snippet; it is your own code with the event listeners removed.

Get the right path to your snapshot with the right and make the change directly, without waiting for a data change.

switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            Date c = Calendar.getInstance().getTime();
            SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
            final String date = df.format(c);
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, -1);
            final String previousDate = df.format(cal.getTime());
            final int[] i = {0};
            if (switch1.isChecked()) {
                Query equery = present.orderByChild("email").equalTo(email);
                // TODO Change this:
                DataSnapshot dataSnapshot = equery.doSomethingToGettheSnapshot()

                        if (!dataSnapshot.exists()) {
                            String code = "1";
                            PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
                            String uploadId = present.push().getKey();
                            present.child(uploadId).setValue(presentStu);
                        } else {
                            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                                String eemail = snapshot.child("email").getValue().toString();
                                String ddate = snapshot.child("date").getValue().toString();
                                if (eemail.equals(eemail) && ddate.equals(date)) {
                                    i[0]++;
                                    break;
                                }
                            }
                           // Toast.makeText(User.this,""+i[0]+"",Toast.LENGTH_SHORT).show();
                                if (i[0] < 1){
                                    String code = "1";
                                    PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
                                    String uploadId = present.push().getKey();
                                    present.child(uploadId).setValue(presentStu);
                                }
                            }
                    }

            } else {
                Query equery = present.orderByChild("email").equalTo(email);

                // TODO Change this:
                DataSnapshot dataSnapshot = equery.doSomethingToGettheSnapshot()

                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                            String eemail = snapshot.child("email").getValue().toString();
                            String ddate = snapshot.child("date").getValue().toString();
                            if (eemail.equals(eemail) && ddate.equals(previousDate)) {
                                present.child(dataSnapshot.getChildren().iterator().next().getKey()).child("code").setValue("0");
                            }
                            if (eemail.equals(eemail) && ddate.equals(date)) {
                                snapshot.getRef().removeValue();
                                break;
                            }
                        }

                    }
            }
        }
    });
Michiel
  • 767
  • 4
  • 19