read
The idea is expose some code to have a reference on how to query and push things to Firebase Realtime Database to create a 1-1 chat with:
- List of channels with me and someone involved.
- Channel with all messages between me and other user
Channel: 1-1 chat
Dependencies
Note: Firebase DB UI is really cool and simple to list Firebase database objects and queries, check it out
Firebase Database usage
Structure
Firebase Realtime Database use JSON to define the database structure (yeah, at the end it will be a BIG JSON). So our database will look like:
Check Structure Data Guide
Database usage
We can query messages, channels and push messages into a channel with the next code:
Note: we used some extensions to make Firebase calls and zip all the results in a easy way (will be better to use Firebase transactions instead ?)
Notes
- For mesasges I used
push
from Firebase Realtime Database to avoid id conflicts - If you want to make queries you should use any of
orderBy
functions. - Because the database is a JSON,
FirebaseDatabase.getInstance().reference.child("messages")
, will get aDatabaseReference
for all the messages but as the direct child of messages is an id (remember note 1.), you should use.orderByChild("channelId")
and.equalTo("channelIdValue")
to get all the children inside messages that havechannelId == "channelIdValue"
(query by children of children attributes) - Databases are created with just users authenticated with firebase auth read/write permissions, but you can make it public for read/write too, it’s ultra insecure, please dont.
- To show the items you can use
FirebaseRecyclerAdapter
fromFirebase Database UI
package, check Full post gist for a sample.
Thanks
Barista Ventures and Oscar Rendon for the support and help.