Modern Apps git

← Modern-Apps.git

contacts: don't rename the default account, and report save failures (#558)

Commit
0f8f5b9bc0c59e3ef21ab13c76a43166b7924260
Author
vayun-mathur <[email protected]>
When
2026-08-23 14:40 UTC (3 months ago)
Parents
9c8fe3e

Diff

contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.ktindex b03eb59779..ad873b3157 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/Contact.kt@@ -253,7 +253,8 @@ data class Contact(     val note: Note         get() = details.notes.first() -    fun save(context: Context, newDetails: ContactDetails, oldDetails: ContactDetails) {+    /** Returns false if the provider rejected the batch; never throws. */+    fun save(context: Context, newDetails: ContactDetails, oldDetails: ContactDetails): Boolean {         val ops = ArrayList<ContentProviderOperation>()         if (id == 0L) {             ops += ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)@@ -274,7 +275,13 @@ data class Contact(             // details             ops += handleDetailUpdates(oldDetails.all(), newDetails.all(), id.toString())         }-        context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops)+        return try {+            context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops)+            true+        } catch (e: Exception) {+            Log.e("Contact", "Error saving contact", e)+            false+        }     }      private fun handleDetailUpdates(currentDetails: List<ContactDetail<*>>, newDetails: List<ContactDetail<*>>, rawContactID: String): List<ContentProviderOperation> {
contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.ktindex 24f8203bee..899263cb0a 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/SimContacts.kt@@ -40,6 +40,15 @@ fun isSimAccountType(type: String?): Boolean = type == SIM_ACCOUNT_TYPE  */ fun isLocalAccountType(type: String?): Boolean = type.isNullOrBlank() || type == LOCAL_ACCOUNT_TYPE +/**+ * True for the implicit device-local account, which the provider identifies by having+ * *neither* an account name nor a type. It cannot be renamed: the provider requires an+ * account to specify both fields or neither, so a name-only rename leaves rows it+ * rejects on the next insert.+ */+fun isDefaultLocalAccount(name: String?, type: String?): Boolean =+    name.isNullOrBlank() && type.isNullOrBlank()+ object SimContactsDataSource {      private const val TAG = "SimContacts"
contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.ktindex a0da1d55f2..1deb8a7912 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/SettingsPage.kt@@ -25,6 +25,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat+import com.vayunmathur.contacts.data.isDefaultLocalAccount import com.vayunmathur.contacts.data.isLocalAccountType import com.vayunmathur.contacts.util.ContactAccount import com.vayunmathur.contacts.util.ContactViewModel@@ -217,7 +218,9 @@ fun SettingsPage(viewModel: ContactViewModel, backStack: NavBackStack<Route>) {                     supportingContent = { Text(account.type) },                     trailingContent = {                         Row(verticalAlignment = Alignment.CenterVertically) {-                            if (isLocalAccountType(account.type)) {+                            if (isLocalAccountType(account.type) &&+                                !isDefaultLocalAccount(account.name, account.type)+                            ) {                                 OverflowMenu(icon = { IconMoreVert() }) {                                     Item(                                         text = stringResource(UiR.string.rename),
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.ktindex 96066622fb..06c488b62a 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt@@ -37,6 +37,7 @@ import com.vayunmathur.contacts.data.LOCAL_ACCOUNT_TYPE import com.vayunmathur.contacts.data.SimContact import com.vayunmathur.contacts.data.SimContactsDataSource import com.vayunmathur.contacts.data.isSimAccountType+import com.vayunmathur.contacts.data.isDefaultLocalAccount import com.vayunmathur.contacts.data.isLocalAccountType import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.Dispatchers@@ -422,6 +423,10 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)                 withContext(Dispatchers.Main) { onResult?.invoke(false, "not_local") }                 return@launch             }+            if (isDefaultLocalAccount(account.name, account.type)) {+                withContext(Dispatchers.Main) { onResult?.invoke(false, "not_local") }+                return@launch+            }             if (trimmed.isEmpty()) {                 withContext(Dispatchers.Main) { onResult?.invoke(false, "blank") }                 return@launch@@ -489,6 +494,10 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)                 withContext(Dispatchers.Main) { onResult?.invoke(false, "not_local") }                 return@launch             }+            if (isDefaultLocalAccount(account.name, account.type)) {+                withContext(Dispatchers.Main) { onResult?.invoke(false, "not_local") }+                return@launch+            }             withContext(Dispatchers.IO) {                 try {                     val resolver = getApplication<Application>().contentResolver@@ -649,7 +658,11 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)                     .withValue(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, groupId)                     .build())             }-            resolver.applyBatch(ContactsContract.AUTHORITY, ops)+            try {+                resolver.applyBatch(ContactsContract.AUTHORITY, ops)+            } catch (e: Exception) {+                Log.e("ContactViewModel", "Error adding contacts to group", e)+            }         }     } @@ -663,7 +676,11 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)                         arrayOf(contactId.toString(), ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE, groupId.toString()))                     .build())             }-            resolver.applyBatch(ContactsContract.AUTHORITY, ops)+            try {+                resolver.applyBatch(ContactsContract.AUTHORITY, ops)+            } catch (e: Exception) {+                Log.e("ContactViewModel", "Error removing contacts from group", e)+            }         }     } @@ -679,41 +696,44 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)     }      override fun saveContact(contact: com.vayunmathur.contacts.data.Contact) {-        viewModelScope.launch(Dispatchers.IO) {-            if (isSimAccountType(contact.accountType)) {-                val subId = contact.accountName?.toIntOrNull()-                val name = contact.name.value.trim().ifEmpty { contact.nickname.nickname.trim().ifEmpty { contact.details.phoneNumbers.firstOrNull()?.number?.trim() ?: "" } }-                val number = contact.details.phoneNumbers.firstOrNull()?.number?.trim() ?: ""-                val email = contact.details.emails.firstOrNull()?.address?.trim()?.takeIf { it.isNotEmpty() }-                if (name.isBlank() && number.isBlank()) {-                    Log.w("ContactViewModel", "SIM save skipped: name and number empty")-                    return@launch-                }-                val isExisting = contact.id < 0-                var oldSc: SimContact? = null-                if (isExisting) {-                    oldSc = SimContactsDataSource.listSimContacts(getApplication()).firstOrNull { SimContactsDataSource.syntheticIdFor(it) == contact.id }-                    if (oldSc == null) oldSc = SimContactsDataSource.findBackingSimContact(getApplication(), contact)-                    if (oldSc != null) {-                        // Skip if no actual change-                        if (oldSc.name == name && oldSc.number == number && oldSc.emails == email && oldSc.subscriptionId == subId) {-                            return@launch-                        }-                        SimContactsDataSource.deleteSimContact(getApplication(), oldSc)+        viewModelScope.launch(Dispatchers.IO) { persistContact(contact) }+    }++    /** Writes [contact] to the SIM or the contacts provider. Returns false if the write failed. */+    private suspend fun persistContact(contact: com.vayunmathur.contacts.data.Contact): Boolean {+        if (isSimAccountType(contact.accountType)) {+            val subId = contact.accountName?.toIntOrNull()+            val name = contact.name.value.trim().ifEmpty { contact.nickname.nickname.trim().ifEmpty { contact.details.phoneNumbers.firstOrNull()?.number?.trim() ?: "" } }+            val number = contact.details.phoneNumbers.firstOrNull()?.number?.trim() ?: ""+            val email = contact.details.emails.firstOrNull()?.address?.trim()?.takeIf { it.isNotEmpty() }+            if (name.isBlank() && number.isBlank()) {+                Log.w("ContactViewModel", "SIM save skipped: name and number empty")+                return false+            }+            val isExisting = contact.id < 0+            var oldSc: SimContact? = null+            if (isExisting) {+                oldSc = SimContactsDataSource.listSimContacts(getApplication()).firstOrNull { SimContactsDataSource.syntheticIdFor(it) == contact.id }+                if (oldSc == null) oldSc = SimContactsDataSource.findBackingSimContact(getApplication(), contact)+                if (oldSc != null) {+                    // Skip if no actual change+                    if (oldSc.name == name && oldSc.number == number && oldSc.emails == email && oldSc.subscriptionId == subId) {+                        return true                     }+                    SimContactsDataSource.deleteSimContact(getApplication(), oldSc)                 }-                val ok = SimContactsDataSource.insertSimContact(getApplication(), name, number, email, subId)-                if (!ok) Log.e("ContactViewModel", "Failed to insert SIM contact")-                syncFromSystem()-            } else {-                val contactId = contact.id-                val details = contact.details-                val oldDetails = contacts.value.find { it.id == contactId }?.details-                    ?: _allContacts.value.find { it.id == contactId }?.details-                    ?: com.vayunmathur.contacts.data.ContactDetails.empty()-                contact.save(getApplication(), details, oldDetails)             }+            val ok = SimContactsDataSource.insertSimContact(getApplication(), name, number, email, subId)+            if (!ok) Log.e("ContactViewModel", "Failed to insert SIM contact")+            syncFromSystem()+            return ok         }+        val contactId = contact.id+        val details = contact.details+        val oldDetails = contacts.value.find { it.id == contactId }?.details+            ?: _allContacts.value.find { it.id == contactId }?.details+            ?: com.vayunmathur.contacts.data.ContactDetails.empty()+        return contact.save(getApplication(), details, oldDetails)     }      // ---------------------------------------------------------------------@@ -989,20 +1009,26 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)             ),             groups = draft.groupMemberships         )-        // For existing SIM contacts, keep synthetic id so saveContact can locate old row+        // For existing SIM contacts, keep synthetic id so saveContact can locate old row.+        // The provider requires an account to name both fields or neither, so a draft pointing at+        // a half-renamed account saves to device-local rather than being rejected.+        val accountType = draft.accountType.ifEmpty { null }+        val accountName = if (accountType == null) null else draft.accountName.ifEmpty { null }         val newContact = original?.copy(-            accountType = draft.accountType.ifEmpty { null }?.let { it },-            accountName = draft.accountName.ifEmpty { null },+            accountType = accountType,+            accountName = accountName,             details = details         ) ?: Contact(             id = 0,-            accountType = draft.accountType.ifEmpty { null },-            accountName = draft.accountName.ifEmpty { null },+            accountType = accountType,+            accountName = accountName,             isFavorite = false,             details = details         )-        saveContact(newContact)-        clearEditDraft()-        onResult?.invoke(true, null)+        viewModelScope.launch {+            val ok = withContext(Dispatchers.IO) { persistContact(newContact) }+            if (ok) clearEditDraft()+            onResult?.invoke(ok, null)+        }     } }