firebase How do I listen for errors when accessing the database? Detect errors when writing a value on Android


There are many reasons a write operation may fail. A frequent one is because your security rules reject the operation, for example because you're not authenticated (by default a database can only be accessed by an authenticated user).

You can see these security rule violations in the logcat output. But it's easy to overlook these. You can also handle them in your own code and make them more prominently visible, which is especially useful during development (since your JSON, rules and code change often).

To detect a failed write on Android you attach a completion callback to setValue:

ref.setValue("My new value", new DatabaseReference.CompletionListener() {
    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
        throw databaseError.toException();

Throwing an exception like this ensures that it will be very difficult to overlook such an error next time.