0

I'm working with an Android App that functions as an instant messaging service, and I'm at the point of pulling the message data through into a RecyclerView. I have my Firebase Query object returning all the messages that match the id of the chat that has been loaded, this is done like so:

Query qChatMessages = mDbRefMessages
    .orderByChild("messageChat")
    .equalTo(mChatId);

So far so good, and this is returning the collection of messages that I expect. The problem is now that, upon passing them to the RecyclerView to be displayed, they come out in the inverse order of how you would typically expect an instant messenger to display, so the messages are actually getting older as you scroll down the chat.

My message nodes in the database all have a messageTimestamp field associated with them, so this is what I would want to sort the data by. The problem is that I don't seem to be able to find a way of ordering the data by any field other than the one that I'm querying on, or getting the results back from Firebase and subsequently ordering them.

Does anyone know how I can work around this, or if there's some Firebase capabilities I'm not aware of?

Thanks in advance,

Mark

marcuthh
  • 592
  • 3
  • 16
  • 42

1 Answers1

1

The easiest way is to store an extra piece of data in your message nodes which is the epoch time multiplied by -1: this way you can sort on this field and the query will return the right order.

See this post on how to get the epoch time: how to get the number of seconds passed since 1970 for a date value?


However, note that with your current data structure, you will encounter a problem: you will need to sort on this new data (e.g. with .orderByChild("messageCreationTime")) AND filter for a given mChatId (e.g. with equalTo(mChatId)), which is not possible.

So, you would have to re-structure your database (if this is possible) like this:

- messages
   - mChatId
      - messageUniqueID  <- most probably auto-generated by Firebase
        - messageTitle: ....
        - messageCreationTime: -1525857044

And you would query by:

Query qChatMessages = databaseReference.child("messages").child(mChatId)
        .orderByChild("messageCreationTime");
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • Thanks for this, would you mind dropping me a quick example of how this would look in the code? – marcuthh May 09 '18 at 08:48
  • @marcuthh You mean the query code or the code to write this extra data? In the second case, you would need to update your original post with the code you use for writing a new `message`. – Renaud Tarnec May 09 '18 at 08:52