0

I'm trying to make it so when a user loses the connection to the database they get sent to the previous activity. However, what ends up happening is that on the activities creation, this database reference returns false and immediately boots the user back to the previous screen in which case they have to try again. Why is Firebase returning false as soon as this reference is obtained and what can I do to prevent that?

The obvious solution is to add a sort of switch once the user is connected that then allows the disconnected section to trigger. However, I would like to know what causes false to be returned immediately and how to prevent it from doing so. Thank you.

DatabaseReference referenceConnection = database.getReference(".info/connected");
        referenceConnection.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                boolean isConnected = snapshot.getValue(Boolean.class);

                if(isConnected){
                        Log.e("CONNECTION", "REGAINED");
                        searchForRooms();
                }
                else{
                        // This returns immediately despite being connected
                        Log.e("CONNECTION", "LOST");
                        finish();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
  • See https://stackoverflow.com/a/46294911, https://stackoverflow.com/a/51193338 and probably more from this: https://www.google.com/search?q=Firebase+%E2%80%9C.info%2Fconnected%E2%80%9D+returns+false+initially+then+true – Frank van Puffelen Aug 22 '20 at 23:47

1 Answers1

0

Why is Firebase returning false as soon as this reference is obtained and what can I do to prevent that?

The SDK does not consider itself "connected" until it's able to make its first connection to the server. Until then, it is disconnected. It does not initially start out as "connected".

If you want some activity to start only when the app is connected, you will have to wait until it becomes connected before starting it.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thank you that clears it up. So basically for what I want, setting the user's online/offline status with a onDisconnect() is the best course of action so that on reconnection it reads the change and boots the user out to the previous activity. –  Aug 22 '20 at 21:34