[英]How do I generate a unique key for each message in Realtime Database?
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.
实时聊天将通过 Firebase 实时数据库完成,然后一段时间后消息将被移动到 Firestore。
This is the structure I'm thinking of for RTDB.这是我为 RTDB 考虑的结构。 The groupID will be the first node after the root DB node.
groupID 将是根 DB 节点之后的第一个节点。 The next child under the groupID node will be the message that each user sends.
groupID 节点下的下一个子节点将是每个用户发送的消息。 This node will contain the createdate, the actual message, the user's uid, and the user's username.
此节点将包含 createdate、实际消息、用户的 uid 和用户的用户名。
However, I'm not sure how to generate a unique key in the place of MessageKey and MessageKey2 below.但是,我不确定如何在下面的 MessageKey 和 MessageKey2 位置生成唯一密钥。 How do I generate something unique to insert in there?
我如何生成一些独特的东西来插入那里?
Note: I tried getting the key from database.push()
but it gave me this: https://APPNAME-cf4da.firebaseio.com/-M_hwyb15XnNDjGDaO7X注意:我尝试从
database.push()
获取密钥,但它给了我这个: https://APPNAME-cf4da.firebaseio.com/-M_hwyb15XnNDjGDaO7X
Would I just need to strip off that root node to use this as MessageKey?我只需要剥离该根节点即可将其用作 MessageKey 吗?
Looking at the URL, is the key being added to root of db rather than inside of group ID node?查看 URL,密钥是否添加到 db 的根目录而不是组 ID 节点内部? 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. @Louis 在评论中建议的其他选项是使用 UUID,就像这样。
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.如果仍有问题,请在评论中告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.