简体   繁体   中英

Query multiple nodes for Recycler View?

I have my Firebase DB setup like so,

I want to retrieve the childs pointed to by the blue arrows. They are the last messages in each chat. I want to use the values to fill a RecyclerView. However, in order to retrieve all the last messages in each chat I have to do multiple queries and the RecyclerView requires a single query. Or so it seems to be the case from what I've googled so far.

Another solution I tried was to create a ListView and fill it with a custom adapter. Then by doing multiple queries I can fill a list and use that instead of a query. However, in order to fill the list I need to make it final in the local scope of a snapshot. That doesn't work because I have two snapshots.

I have thought of simply redesigning my DB however, I can't think of a way to do it without making the DB unorganized. Any help or suggestions is greatly appreciated.

The only way to do this with your current data structure is, as you've already noticed, with a separate query for each node under chat .

As usual with NoSQL databases, the solution is to modify/augment the data model to make the use-case easier. In this case, I'd store the information you need directly under a new top-level node.

lastChatMessages: {
  "0hV9...Ri83": {
    ...
  },
  "IZsn...QHn2": {
    ...
  }
}

So whenever you add a new message to /chats , you also set the same information in /lastChatMessages with the same first-level child ID.

This sort of data duplication is quite common in NoSQL databases. If that's new to you, I'd recommend reading NoSQL data modeling , watching Firebase for SQL developers , and possible also Getting to know Cloud Firestore . That last one is for Cloud Firestore, but most concepts apply to many NoSQL databases.

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