Reputation: 51
data class Message(
var message:String,
var id:String,
var receiverID:String,
@ServerTimestamp
var date: Date? = null,
var isChecked:Boolean,
var type:String,
)
This is the model of my message
val message = Message(text, id, receiverUser.uid, null, false, MESSAGE_TYPE_TEXT)
database
.collection(KEY_COLLECTION_USERS)
.document(preferenceManager.getString(KEY_USER_ID)!!)
.collection(KEY_COLLECTION_CHAT)
.add(message)
mBinding.typeMessageField.setText(null)
This is how I add a message, I pass the date value as null
so it generates itself, but I don't understand how I can get the generated time from there to display it on the screen and sort the list of messages, because when I try to get the value, I can't translate it to date, or I get NullPointerException.
database
.collection(KEY_COLLECTION_USERS)
.document(preferenceManager.getString(KEY_USER_ID)!!)
.collection(KEY_COLLECTION_CHAT)
.addSnapshotListener { value, error ->
var messages_test = ArrayList(messages)
if (error != null) {
return@addSnapshotListener
} else {
if (value == null) {
return@addSnapshotListener
} else {
for (documentChange in value.documentChanges) {
if (documentChange.type == DocumentChange.Type.ADDED) {
var doc = documentChange.document
if (doc.getString(KEY_MESSAGE_RECEIVER_ID) == receiverUser.uid) {
var text = doc.getString(KEY_MESSAGE).toString()
var id = doc.getString(KEY_MESSAGE_ID).toString()
var receiverId =
doc.getString(KEY_MESSAGE_RECEIVER_ID).toString()
var date = doc.getTimestamp(KEY_MESSAGE_DATE)?.toDate()
var isChecked = doc.getBoolean(KEY_MESSAGE_ISCHECKED)!!
var type = doc.getString(KEY_TYPE_MESSAGE).toString()
var message =
Message(text, id, receiverId, date, isChecked, type)
if (message !in messages) {
messages.add(message)
}
}
}
}
messages.sortBy { it -> it.date }
var messages_test = ArrayList(messages)
userChatAdpater.updateList(messages_test)
if (messages.size != 0) {
mBinding.rvUserChat.smoothScrollToPosition(messages.size - 1)
}
}
}
}
This is message listener
Upvotes: 0
Views: 147
Reputation: 138944
When you pass in the constructor null
to the date
field, that field will have the value of null in the database. Which most likely is not what you want. To solve this, when you create an object of type Message class, don't pass anything to the date
field. Firebase servers will read your date
field, as it is a ServerTimestamp (see the annotation), and it will populate that field with the server timestamp accordingly. So you should have something like this:
val message = Message(text, id, receiverUser.uid, false, MESSAGE_TYPE_TEXT)
See, there is no null
value. However, the field should remain the same in your class:
@ServerTimestamp
var date: Date? = null,
Don't delete null from the class.
Upvotes: 2