firebase How do I listen for errors when accessing the database? Detect errors when reading data on Android

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

A frequent reason why your read operation may not work 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 read on Android you must implement the onCancelled method of your ChildEventListener:

databaseRef.addChildEventListener(new ChildEventListener() {
    public void onChildAdded(DataSnapshot dataSnapshot, String s) { ... }
    public void onChildChanged(DataSnapshot dataSnapshot, String s) { ... }
    public void onChildRemoved(DataSnapshot dataSnapshot) { ... }
    public void onChildMoved(DataSnapshot dataSnapshot, String s) { ... }
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});

Or if you have a ValueEventListener:

databaseRef.addValueEventListener(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot, String s) { ... }
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});

With this code in place it will be pretty hard to overlook a security error when reading data on Android.



Got any firebase Question?