Fix crash when returning to scheduled message screen after scheduling message

This commit is contained in:
Moez Bhatti
2018-09-19 16:03:58 -04:00
parent abff121931
commit 76a5c9e3ec
@@ -29,13 +29,11 @@ import com.moez.QKSMS.common.base.QkRealmAdapter
import com.moez.QKSMS.common.base.QkViewHolder
import com.moez.QKSMS.common.util.DateFormatter
import com.moez.QKSMS.model.Contact
import com.moez.QKSMS.model.PhoneNumber
import com.moez.QKSMS.model.Recipient
import com.moez.QKSMS.model.ScheduledMessage
import com.moez.QKSMS.repository.ContactRepository
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import io.realm.RealmList
import kotlinx.android.synthetic.main.scheduled_message_list_item.view.*
import javax.inject.Inject
@@ -45,7 +43,7 @@ class ScheduledMessageAdapter @Inject constructor(
) : QkRealmAdapter<ScheduledMessage>() {
private val contacts by lazy { contactRepo.getContacts() }
private val contactMap: HashMap<String, Contact> = hashMapOf()
private val contactCache = ContactCache()
private val imagesViewPool = RecyclerView.RecycledViewPool()
val clicks: Subject<Long> = PublishSubject.create()
@@ -68,19 +66,11 @@ class ScheduledMessageAdapter @Inject constructor(
val message = getItem(position)!!
val view = holder.itemView
message.recipients.forEach { address ->
if (!contactMap.containsKey(address)) {
contactMap[address] = contacts
.firstOrNull { it.numbers.any { number -> PhoneNumberUtils.compare(address, number.address) } }
?: Contact(numbers = RealmList(PhoneNumber(address)))
}
}
// GroupAvatarView only accepts recipients, so map the phone numbers to recipients
view.avatars.contacts = message.recipients.map { address -> Recipient(address = address) }
view.recipients.text = message.recipients.joinToString(",") { address ->
contactMap[address]?.name?.takeIf { it.isNotBlank() } ?: address
contactCache[address]?.name?.takeIf { it.isNotBlank() } ?: address
}
view.date.text = dateFormatter.getScheduledTimestamp(message.date)
@@ -91,4 +81,24 @@ class ScheduledMessageAdapter @Inject constructor(
view.attachments.isVisible = message.attachments.isNotEmpty()
}
/**
* Cache the contacts in a map by the address, because the messages we're binding don't have
* a reference to the contact.
*/
private inner class ContactCache : HashMap<String, Contact?>() {
override fun get(key: String): Contact? {
if (super.get(key)?.isValid != true) {
set(key, contacts.firstOrNull { contact ->
contact.numbers.any {
PhoneNumberUtils.compare(it.address, key)
}
})
}
return super.get(key)?.takeIf { it.isValid }
}
}
}