2

I'm not sure it's disconect or DatabaseErrors event. First I have a dialog show when start loading data on Firebase, and then I want to dismiss that dialog in two case :

  1. have internet: load data success, and I dissmiss dialog in onDataChange.

  2. no internet connection or turn off wifi quickly when app start.

In second case, I think It's will call onCancelled, and in that method, I will dismiss dialog. But in real, it's not call onCancelled.

So, how I can dissmiss dialog on second case. Here's my code

private void getCategory() {
    mDatabase = FirebaseDatabase.getInstance().getReference();
    mDatabase.child(ReferenceToFirebase.CHILD_CATEGORIES)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //do something

                    //then dismiss dialog
                    mDialog.dismiss();
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    mDialog.dismiss();
                }
            });
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Ton
  • 113
  • 5

1 Answers1

1

onCancelled() is called when the server rejects the listener, typically when the user doesn't have permission to access the data.

You'll probably want to prevent attaching the listener if you don't have a connection to the Firebase Database. For that you can listen to .info/connected and only attach the listener when that is true.

mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference connectedRef = mDatabase.child(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    boolean connected = snapshot.getValue(Boolean.class);
    if (connected) {
        mDatabase.child(ReferenceToFirebase.CHILD_CATEGORIES)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //do something

                    //then dismiss dialog
                    mDialog.dismiss();
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    System.err.println("Listener was cancelled");
                    mDialog.dismiss();
                }
        });
    } else {
      System.out.println("not connected");
      mDialog.dismiss();
    }
  }

  @Override
  public void onCancelled(DatabaseError error) {
    System.err.println("Listener was cancelled");
  }
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • (Additionally) I think it's worth commenting that Firebase has no timeouts and will never call onFailure with an IO. – JacksOnF1re Nov 22 '18 at 14:29