0

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?

TrackDave
  • 279
  • 2
  • 14

2 Answers2

1

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:

Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645
  • A beta testing client of mine has the app installed on his mobile device (always with network connection) and wi-fi tablet (not always connected). The issue we ran into is that when his tablet was offline he wrote a lot of data. He couldn't connect to internet so he repeated the write with his mobile phone, but once his tablet received a connection, the data wrote again duplicating data. So I guess the best method would be to check for connection before writing to the server, is that correct? – TrackDave Dec 02 '17 at 15:23
  • There is no single way that is best. In the way you've currently implemented it, the last write wins. That may be what you want or not. If not, you could indeed not write while offline (or use a transaction, which won't work while you're offline), but that's just as often an inconvenience for your users when they just have a spotty connection. Another way would be to add a timestamp to each update, and then reject writes in security rules if their timestamp is older than the current value. – Frank van Puffelen Dec 02 '17 at 15:39
  • Thanks Frank. I think it is best to leave it the way it is and let the delay happen for those with spotty connection. I just won't allow devices with no connection to be able to hit the add button or something. By the way I love your firecasts! – TrackDave Dec 02 '17 at 19:44
1

You can use the thread in order to check if a connection is available, since firebase does not provide methods to check that: How to check currently internet connection is available or not in android