这一次,我要用 FirBase RealTimeDb实时数据库写个聊天的demo,在存储数据和查询数据时需要规划一下json数据格式,要不然后期就蒙圈了,google的官方文章如下:
https://firebase.google.com/docs/database/android/structure-data
为举例说明为什么嵌套数据不正确,现假设一个如下所示的多层嵌套结构:
{
// This is a poorly nested data architecture, because iterating the children
// of the "chats" node to get a list of conversation titles requires
// potentially downloading hundreds of megabytes of messages
"chats": {
"one": {
"title": "Historical Tech Pioneers",
"messages": {
"m1": { "sender": "ghopper", "message": "Relay malfunction found. Cause: moth." },
"m2": { ... },
// a very long list of messages
}
},
"two": { ... }
}
}
若采用这种嵌套设计,循环访问数据就会出现问题。例如,要列出聊天对话标题,就需要将整个 chats 树(包括所有成员和消息)都下载到客户端。
平展数据结构
如果数据被拆分到不同路径(又称反规范化),则可根据需要通过不同调用有效地下载。 请考虑此平面化结构:
{
// Chats contains only meta info about each conversation
// stored under the chats's unique ID
"chats": {
"one": {
"title": "Historical Tech Pioneers",
"lastMessage": "ghopper: Relay malfunction found. Cause: moth.",
"timestamp": 1459361875666
},
"two": { ... },
"three": { ... }
},
// Conversation members are easily accessible
// and stored by chat conversation ID
"members": {
// we'll talk about indices like this below
"one": {
"ghopper": true,
"alovelace": true,
"eclarke": true
},
"two": { ... },
"three": { ... }
},
// Messages are separate from data we may want to iterate quickly
// but still easily paginated and queried, and organized by chat
// converation ID
"messages": {
"one": {
"m1": {
"name": "eclarke",
"message": "The relay seems to be malfunctioning.",
"timestamp": 1459361875337
},
"m2": { ... },
"m3": { ... }
},
"two": { ... },
"three": { ... }
}
}
官方的建议还是要才用的,淡然,我觉得官方给的第二层结构"members"这个对我来说并没有什么用,于是我打算把它去掉,google核心的思想就是避免嵌套,遵循这一原则,我稍微修改了官方的json结构最终是下面的.
存储聊天内容的json
{
"chats": {
chatlist: [
{
{
"title": "Historical Tech Pioneers",
"lastMessage": "ghopper: Relay malfunction found. Cause: moth.",
"timestamp": 1459361875666,
"member": "天涯恋",
"fridlogo": "pic",
"messageid": "青青"
}
}
]
},
"messages": {
"messages": {
"青青": {[
{
"name": "eclarke",
"message": "The relay seems to be malfunctioning.",
"timestamp": 1459361875337
}]
}
}
}
在chats对象中可以查看到聊天的数量,和哪个好友,头像,时间,对方id,拿到id后可以在message信息中获取好友的聊天记录
存储用户信息的json,这个没啥好说的,保存所有用户的信息
{
users:{userid:
{
"id": "00000000-0000-0000-0000-000000000000",
"createTime": "0001-01-01 00:00:00",
"level": 0,
"nick": "string",
"gender": false,
"birthday": "0001-01-01 00:00:00",
"cellphoneNumber": "string",
"emailAddress": "string",
"name": "string",
"picture": "string""address": "string"
}
}
}