Issue
I'm messing around with Cloud Firestore.
I would like to simply get a callback when reading from DB fails, so I can show a dialog to the user about he has no internet connection. Of course, this would need sophisticated exception handling, but first things first, I would like to just simply get a callback when the app cannot reach the server.
HOWEVER, whenever I test my application with an emulator which has no internet connection, I still get successful callbacks.
This is the log:
Logging_: onSuccess
Logging_: onComplete
Logging_: Task was successful without an internet connection, how?
How is it possible? Am I thinking right that Cloud Firestore is simply not available for this use case since it was built to provide cached data and aggressive syncing in order to provide a seamless user experience even when there is no internet connection?
I would just need a way to just KNOW whether the DB is reachable. (a.k.a - Is there an internet connection problem?)
Code is really simple, it just tries to reach for the current account's characters.
db.collection("users")
.document(accountId)
.collection("characters")
.get()
.addOnCanceledListener(new OnCanceledListener() {
@Override
public void onCanceled() {
Log.i("Logging_", "onCanceled");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.i("Logging_", "onFailure");
}
})
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
Log.i("Logging_", "onSuccess");
}
})
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
Log.i("Logging_", "onComplete");
if (task.isSuccessful()) {
Log.i("Logging_", "Task was successful without internet connection, how?");
} else {
Log.i("Logging_", "Task wasn't successful.");
}
}
});
Solution
I would like to simply get a callback when reading from DB fails, so I can show a dialog to the user about whether he has no internet connection.
The Firestore SDK doesn't throw an error when there is no internet connection, and it makes sense since Firestore is designed to work offline. Behind the scenes, Firestore SDK tries to reconnect until the devices regain connectivity. So not having an internet connection cannot be considered a failure. If you want to check for internet connectivity, the following answer might help:
Please notice that Firestore has a built-in mechanism that can help know when an error occurs. So the failure callback occurs when Firestore servers reject the request due to a security rule issue.
There is a solution in which you can force the retrieval of data only from the cache or from the server. Here is the official documentation regarding source options:
Answered By - Alex Mamo
Answer Checked By - Willingham (JavaFixing Volunteer)