我在firestore中进行了一次聊天,显然我需要从每个聊天室获取消息,但是消息永远不会按照日期和用户ID进行排序。
一开始我没有使用@ServerTimestamp,而是在Android设备本身上生成日期,但是根据Stackoverflow的建议,我改用了Firestore来生成日期,根据可以解决的建议,但是不起作用。它以我未订购的顺序排列,以用户ID lateinit var from_id: String
class Message {
lateinit var content: String
@ServerTimestamp
var timestamp: Timestamp ?= null
lateinit var from_id: String
lateinit var type: String
constructor(content: String, timestamp : Timestamp, from_id: String, type: String) {
this.content = content
this.from_id = from_id
this.timestamp = timestamp
this.type = type
}
constructor(content: String, from_id: String, type: String) {
this.content = content
this.from_id = from_id
this.type = type
}
constructor()
}
ControllerChat
...
override fun sendMessageText(idChatRoom: String, from_id: String, text: String, listenerSendMessage: ListenerSendChatMessage) {
var message = Message(text, from_id, Message.TEXT)
chatChannelsCollectionRef
.document(idChatRoom)
.collection(MESSAGES)
.add(message).addOnSuccessListener {
listenerSendMessage.onSendChatMessageSucess()
}.addOnFailureListener {
listenerSendMessage.errorSendChatMessage(it)
}
}
...
override fun getAllMessageFromChatRoom(idChatRoom: String, listenerGetAllChatMessage: ListenerGetAllChatMessage) {
Log.d(TAG, "ChatController - getAllMessageFromChatRoom")
listenerSnapshotAllMessageFromChatRoom = chatChannelsCollectionRef
.document(idChatRoom)
.collection(MESSAGES)
.orderBy("timestamp", Query.Direction.ASCENDING)
.addSnapshotListener(object : EventListener<QuerySnapshot> {
override fun onEvent(querySnapshot: QuerySnapshot?, p1: FirebaseFirestoreException?) {
querySnapshot?.let { qSnap ->
if (!qSnap.isEmpty) {
var documentChange = qSnap.documentChanges
for (doc in documentChange) {
var message = doc.document.toObject(Message::class.java)
Log.i(TAG, "Document Change: " + message.content)
listenerGetAllChatMessage.onChatMessage(message)
}
}
}
}
})
}