1

Im using this function for checking a specific date is present in the database or not, but I'm getting false every time and the new date is also updated in the database

 private boolean dateCheck() {
        dateKey = false;
        final ProgressDialog pg = new ProgressDialog(AdminMain.this);
        pg.setMessage("Validating Date");
        pg.setCanceledOnTouchOutside(false);
        pg.setCancelable(false);
        pg.show();
        final DatabaseReference dbDate = FirebaseDatabase.getInstance().getReference("Dates").child(batch).child(sem);
        dbDate.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.hasChild(date)) {
                    pg.dismiss();
                    Snackbar.make(findViewById(android.R.id.content), "Attendance has been already sumbitted", Snackbar.LENGTH_LONG).show();
                    dateKey = false;
                } else {
                    dateKey = true;
                    dbDate.child(date).setValue(true);
                    pg.dismiss();

                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Snackbar.make(findViewById(android.R.id.content), databaseError.getMessage(), Snackbar.LENGTH_SHORT).show();
                pg.dismiss();
                dateKey=false;
            }
        });

        return dateKey;
    }
Rithik Sabhal
  • 59
  • 1
  • 10

1 Answers1

2

When you are returning the dateKey boolean as a result of a method, you are always returning the value that was assigned first, which is false. This is happening because your if statement that exists inside onDataChange() isn't yet triggered when you return that result and that's why is always false. So onDataChange() method returns immediately after it's invoked, and the callback from the Task it returns, will be called some time later.

There are no guarantees about how long it will take. So it may take from a few hundred milliseconds to a few seconds before that data is available. Basically, you're trying to return a value synchronously from an API that's asynchronous. That's not a good idea. You should handle the APIs asynchronously as intended.

A quick solve for this problem would be to use your boolean dateKey only inside the onDataChange() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193