
Question:
I'm building an app using Firebase Realtime Database and I'm testing out the onFailure callback. I turn off my mobile data and run the code below.
mDatabaseReference.updateChildren(childUpdates)
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(TeamActivity.this, R.string.toast_message_error_add, Toast.LENGTH_LONG).show();
}
});
The issue is that the toast message doesn't pop up, then when I turn back on the mobile data, all of a sudden, my firebase database get populated a few seconds after. Now I understand this should happen when you set FirebaseDatabase.getInstance().setPersistenceEnabled(true), but I don't have this set and don't want it set. The app should show the toast message when the internet connection is off, because it should fail to write. Anyone know why this is happening?
Answer1:The onFailure
callback only triggers when the write is fails on the server, typically because it is rejected by your security rules.
Not having a network connection does not trigger a failure, it merely delays the write to the database server until you're back online again.
Also see:
<ul><li><a href="https://stackoverflow.com/questions/46014436/firebase-database-for-android-write-events-when-offline-using-persistence" rel="nofollow">Firebase database for Android - write events when offline, using persistence</a></li> <li><a href="https://stackoverflow.com/questions/37184941/firebase-offline-no-completionlistener-on-setvalue" rel="nofollow">Firebase offline no CompletionListener on setValue</a></li> <li><a href="https://stackoverflow.com/questions/42591313/firebase-database-query-not-returning-when-offline" rel="nofollow">Firebase database query not returning when offline</a> (on how to detect whether you have a connection)</li> </ul>Answer2:You can use the thread in order to check if a connection is available, since firebase does not provide methods to check that: <a href="https://stackoverflow.com/q/5474089/9015853" rel="nofollow">How to check currently internet connection is available or not in android</a>