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.