Android check firebase connection
Solution 1
The Firebase client doesn't treat the absence of a connection as an error, so it doesn't call your completion listener with an error.
When you call setValue()
while the Firebase client is not connected to its backend, the client keeps the write in a queue. When the connection is restored, it sends the write to the server.
Your completion handler will only be called once the write has been executed by the server. If there was an error (i.e. if the security rules rejected the write), you will get an error passed into the callback.
If you want to know if the client is connected to the server before calling setValue()
, you can attach a listener to .info/connected
.
Solution 2
Did you try adding onFailureListner?
ref.setValue(resultat, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference dataRef) {
if (databaseError == null) {
FragmentManager fm3 = getFragmentManager();
ServerOk serverok = new ServerOk();
serverok.show(fm3, "serverok");
} else {
FragmentManager fm3 = getFragmentManager();
Server server = new Server();
server.show(fm3, "server");
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
// did not set value
}
});
Solution 3
Take a look at the documentation: https://firebase.google.com/docs/reference/android/com/google/firebase/database/DatabaseError
You can check the error type with databaseError.getCode()
and then test it against those listed there. For debugging you can also use databaseError.getMessage()
or databaseError.getDetails()
to get information. You can also print it as a StackTrace
with databaseError.toException().printStackTrace()
.
In your case I guess databaseError.getCode() == DatabaseError.DISCONNECTED
or databaseError.getCode() == DatabaseError.NETWORK_ERROR
, but I am not sure about those. You can just test it yourself. You can of course also just print the code for debugging purposes.
Jean-Philippe Mary
Updated on June 14, 2022Comments
-
Jean-Philippe Mary about 2 years
I am using a firebase database for my Android app. When I submit a score there is a message (fragment serverOK) if it works. I would like a message for all the other cases. There is one if the databaseEror is non null but how to do if it didn't connect to firebase?
Below is my code:
ref.setValue(resultat, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference dataRef) { if (databaseError == null) { FragmentManager fm3 = getFragmentManager(); ServerOk serverok = new ServerOk(); serverok.show(fm3, "serverok"); } else { FragmentManager fm3 = getFragmentManager(); Server server = new Server(); server.show(fm3, "server"); } } });
Thank you for you answers