简体   繁体   中英

Inserting The UID into Firebase Database Only once

In the main activity of Android Studio, immediately after anonymously signing in into firebase, I have this line of code:

        FirebaseDatabase.getInstance().getReference().child("Online Users").push().setValue(currentUser.getUid().toString());

So, the UID of current user will be saved into firebase under the child "Online Users". Good. Problem is, when I open the app for the second or third time, or if I navigate from another activity to the main activity, this line of code gets executed again, and now I have several identical entries in the firebase. I mean, one UID has been pushed into firebase several times. But I don't want that. I want only one copy of each UID there. How can I achieve that?

Whenever you want a specific value to be unique in the Firebase Database, model it as the key of a list.

In your case that means that instead of calling push() you actually use the UID as the key:

FirebaseDatabase.getInstance().getReference().child("Online Users").child(currentUser.getUid().toString()).setValue(true);

Now whenever the user comes online again, they're just writing true to the same location again.


Note that the same user can come online from multiple devices. If you are trying to build a presence system, tracking what users are online, I recommend studying the sample presence system in the Firebase documentation which handles the edge cases correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM