0
votes

I'm working on a simple group chat app. The realtime chatting will be done through Firebase Realtime Database and then after a while the messages will be moved to Firestore.

This is the structure I'm thinking of for RTDB. The groupID will be the first node after the root DB node. The next child under the groupID node will be the message that each user sends. This node will contain the createdate, the actual message, the user's uid, and the user's username.

However, I'm not sure how to generate a unique key in the place of MessageKey and MessageKey2 below. How do I generate something unique to insert in there?

enter image description here

Note: I tried getting the key from database.push() but it gave me this: https://APPNAME-cf4da.firebaseio.com/-M_hwyb15XnNDjGDaO7X

Would I just need to strip off that root node to use this as MessageKey?

1
You could always use a UUID. - Louis Wasserman
Your link doesn't go anywhere. What issues are you encountering using push()? - Cole Tustin
To generate unique IDs use push(). If you're having trouble with that, edit your question to show a minimal, complete snippet that reproduces where you got stuck. Right now there's simply not enough information for us to effectively help better than the linked docs (or this codelab) do. - Frank van Puffelen

1 Answers

1
votes

Looking at the URL, is the key being added to root of db rather than inside of group ID node? If yes, then please make sure your database reference is correct. In your case:

String key = mDatabase.child("groupId").push().getKey()
mDatabase.child("groupId").child(key).setValue({}); //Set the required value

Other option as suggested in comments by @Louis is using UUIDs and that goes like this.

String key =  UUID.randomUUID().toString()
mDatabase.child("groupId").child(key).setValue({}); //Set the required value.

Let me know in comments if something is still going wrong.