Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase isSuccessful() always return false

I am using firebase as a backend service.I am inserting data to my firebase database and i check if insertion is successful or not with the following code but it always returns false.

boolean issucessfull = ref.child("universities").setValue(university).isSuccessful();

            if (issucessfull) {
                Toast.makeText(UniversityActivity.this, "added to database successfully", Toast.LENGTH_SHORT).show();
                clearViews();
                enableViews(true);
            } else {
                Toast.makeText(UniversityActivity.this, "Some error occured, try again", Toast.LENGTH_SHORT).show();
                enableViews(true);
            }

What could be reason? i have debugged it data is been added to firebase but it still be false always. Any help would appreciated.

like image 590
Zeeshan Shabbir Avatar asked Sep 20 '25 12:09

Zeeshan Shabbir


1 Answers

It's because the Task has not completed yet, add a CompletionListener instead as a second parameter of setValue.

ref.child("universities").setValue(university, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
        if (databaseError != null) {
            Toast.makeText(UniversityActivity.this, "Some error occured, try again", Toast.LENGTH_SHORT).show();
            enableViews(true);
        } else {
            Toast.makeText(UniversityActivity.this, "added to database successfully", Toast.LENGTH_SHORT).show();
            clearViews();
            enableViews(true);
        }
    }
});

Above code is the recommended way, an alternative is

Task<Void> task = new FireDatabaseRole().ref.setValue(university);
task.addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            // success
        } else {
            // error
        }
    }
});
like image 80
Wilik Avatar answered Sep 22 '25 12:09

Wilik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!