For the past few days i\'ve been trying to show the online/offline status of a user.. For this i have a register activity where they register and their info gets saved in fireba
What you're trying to do is known as a presence system. The Firebase Database has a special API to allow this: onDisconnect()
. When you attach a handler to onDisconnect()
, the write operation you specify will be executed on the server when that server detects that the client has disconnected.
From the documentation on managing presence:
Here is a simple example of writing data upon disconnection by using the
onDisconnect
primitive:DatabaseRef presenceRef = FirebaseDatabase.getInstance().getReference("disconnectmessage"); // Write a string when this client loses connection presenceRef.onDisconnect().setValue("I disconnected!");
In your case this could be as simple as:
protected void onStart() {
super.onStart();
fetchData();
DatabaseReference onlineRef = mDatabaseReference.child("UserData").child(UID).child("Online");
onlineRef.setValue("True");
onlineRef.onDisconnect().setValue("False");
}
Note that this will work in simple cases, but will start to have problems for example when your connection toggles rapidly. In that case it may take the server longer to detect that the client disappears (since this may depends on the socket timing out) than it takes the client to reconnect, resulting in an invalid False
.
To handle these situations better, check out the sample presence system in the documentation, which has more elaborate handling of edge cases.