As in the official documentation regarding getting data, you can get the exception from the task
object like this:
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document");
}
} else {
//Log the error if the task is not successful
Log.d(TAG, "get failed with ", task.getException());
}
}
});
And remember, a Task is complete
when the work represented by the Task is finished, regardless of its success
or failure
. There may or may not have been an error, and you have to check for that. On the orter side, a Task is "successful" when the work represented by the task is finished, as expected, with no errors.
As @Raj mentioned in his answer, you can also use addOnFailureListener
but note, if there is a loss of network connectivity (there is no network connection on user device), neither onSuccess()
nor onFailure()
are triggered. This behavior makes sense, since the task is only considered completed when the data has been committed (or rejected) on the Firebase server. onComplete(Task<T> task)
method is called also only when the Task completes. So in case of no internet connection, neither onComplete
is triggered.