load contact from realm if possible

This commit is contained in:
Moez Bhatti
2017-08-28 16:18:04 -07:00
parent 837f474e97
commit 15c6cc159d
4 changed files with 37 additions and 8 deletions
@@ -5,14 +5,14 @@ import io.realm.annotations.PrimaryKey
open class Contact() : RealmObject() {
@PrimaryKey var id: Long = 0
@PrimaryKey var recipientId: Long = 0
var address: String = ""
/**
* For inflating the contact using the cursor
*/
constructor(id: Long, address: String) : this() {
this.id = id
this.recipientId = id
this.address = address
}
@@ -30,8 +30,8 @@ open class Conversation() : RealmObject() {
Flowable.fromIterable(cursor.getString(ConversationColumns.RECIPIENT_IDS).split(" "))
.map { id -> id.toLong() }
.map { id -> contacts.getContactBlocking(id) }
.filter { contact -> contact.id != 0L }
.map { id -> contacts.getContact(id) }
.filter { contact -> contact.recipientId != 0L }
.blockingSubscribe { contact -> this.contacts.add(contact) }
snippet = cursor.getString(ConversationColumns.SNIPPET) ?: ""
@@ -4,6 +4,7 @@ import android.content.ContentUris
import android.content.Context
import android.net.Uri
import com.moez.QKSMS.data.model.Contact
import io.realm.Realm
class ContactRepository(val context: Context) {
@@ -12,14 +13,42 @@ class ContactRepository(val context: Context) {
*/
private val URI = Uri.parse("content://mms-sms/canonical-address")
fun getContactBlocking(recipientId: Long): Contact {
/**
* This function is not asynchronous, and potentially very slow. Make sure to
* execute off of the main thread. At the time of writing
*/
fun getContact(recipientId: Long): Contact {
var contact: Contact? = getContactFromRealm(recipientId)
if (contact == null) {
contact = getContactFromContentProvider(recipientId)
}
return contact ?: Contact()
}
private fun getContactFromRealm(recipientId: Long): Contact? {
val realm = Realm.getDefaultInstance()
val results = realm.where(Contact::class.java)
.equalTo("recipientId", recipientId)
.findAll()
if (results.size > 0) {
return results[0]
}
return null
}
private fun getContactFromContentProvider(recipientId: Long): Contact? {
var contact: Contact? = null
val cursor = context.contentResolver.query(ContentUris.withAppendedId(URI, recipientId), null, null, null, null)
if (cursor.moveToFirst()) {
return Contact(recipientId, cursor.getString(0))
contact = Contact(recipientId, cursor.getString(0))
}
cursor.close()
return Contact()
return contact
}
}
@@ -9,7 +9,7 @@ class ConversationRepository {
fun getConversation(threadId: Long): RealmResults<Conversation> {
return Realm.getDefaultInstance()
.where(Conversation::class.java)
.equalTo("id", threadId)
.equalTo("recipientId", threadId)
.findAllAsync()
}