Modern Apps git

← Modern-Apps.git

contacts: fix editing SIM and on-device contacts (#888, #889)

Commit
ed2d060deb3af03c59c49994c1d42b9c2a0102cc
Author
Vayun Mathur <[email protected]>
When
2026-10-31 22:09 UTC (1 month ago)
Parents
0e7dc8a
#889 - editing a contact used the last add-screen account:
The edit draft took its account from `contact.accountName ?: last
selected`. On-device contacts have a null account, so they inherited
whatever account was last picked in the add screen, and saving wrote a
new copy into that account while the original stayed untouched. An
existing contact now always keeps its own account (blank = on-device);
only new contacts fall back to the last selected account.

#888 - saving an edited SIM contact showed "Contact not found" or the
old data:
SIM contacts have synthetic ids hashed from subId|name|number|email
(SimContactsDataSource.syntheticIdFor), so every edit gives the row a
new id. The editor popped back to ContactDetail(oldId):
- in-place ADN update: list size unchanged, so the details page's
  produceState (keyed on contactsList.size) kept the stale contact ->
  old data shown;
- delete+insert fallback: the lookup re-ran with the dead id -> "Contact
  not found".
The save now resolves the saved row's new id from the post-save sync
(findSavedSimContactId: name+number, then number, then name, since SIM
cards may truncate names) and returns it via saveEditDraft's callback.
EditContactPage swaps the ContactDetail entry beneath it to the new id
before exiting, so the details page opens the freshly saved contact.
Provider contacts keep their id and are unaffected.

Verified: ./gradlew :contacts:compileDevKotlin, :contacts:lint clean;
./check contacts detekt findings are pre-existing (no functions added
to the files flagged). Not exercised on a device with a physical SIM.

Diff

contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.ktindex 244f679b4f..a19fde2a1a 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/ui/EditContactPage.kt@@ -97,9 +97,19 @@ fun EditContactPage(backStack: NavBackStack<Route>, viewModel: ContactViewModel,             Button(onClick = {                 if (isSaving) return@Button                 isSaving = true-                viewModel.saveEditDraft { ok, err ->+                viewModel.saveEditDraft { ok, err, savedId ->                     isSaving = false-                    if (ok) onExit() else saveError = err ?: context.getString(R.string.save_failed)+                    if (ok) {+                        // A saved SIM contact comes back under a new id; repoint the details+                        // page underneath so it shows the edit instead of "not found"/stale data.+                        if (contactId != null && savedId != null && savedId != contactId) {+                            val idx = backStack.backStack.lastIndexOf(Route.ContactDetail(contactId))+                            if (idx >= 0) backStack.set(idx, Route.ContactDetail(savedId))+                        }+                        onExit()+                    } else {+                        saveError = err ?: context.getString(R.string.save_failed)+                    }                 }             }) {                 Text(stringResource(UiR.string.save))
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelDraft.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelDraft.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelDraft.ktindex 2e3c2e7d7c..b86c546774 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelDraft.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelDraft.kt@@ -109,11 +109,13 @@ private fun ContactViewModel.ContactDraft.withListFields(     commPref = details?.commPref, ) +// An existing contact keeps its own account even when that is on-device (null); only a new+// contact falls back to the last account picked in the add screen. private fun ContactViewModel.draftAccountName(contact: Contact?): String =-    contact?.accountName ?: lastSelectedAccountState.value?.name ?: ""+    if (contact != null) contact.accountName.orEmpty() else lastSelectedAccountState.value?.name.orEmpty()  private fun ContactViewModel.draftAccountType(contact: Contact?): String =-    contact?.accountType ?: lastSelectedAccountState.value?.type ?: ""+    if (contact != null) contact.accountType.orEmpty() else lastSelectedAccountState.value?.type.orEmpty()  private fun ContactViewModel.draftPhoneNumbers(     details: ContactDetails?,@@ -290,20 +292,26 @@ private const val PHOTO_JPEG_QUALITY = 100 /**  * Persists the current draft via the unified save path.  * SIM vs device routing is handled by [saveContact] based on draft.accountType.+ * [onResult] receives the saved contact's id, which differs from the edited one for SIM rows.  */-fun ContactViewModel.saveEditDraft(onResult: ((Boolean, String?) -> Unit)? = null) {+fun ContactViewModel.saveEditDraft(onResult: ((Boolean, String?, Long?) -> Unit)? = null) {     val draft = editDraftState.value ?: return     // For SIM accounts, validate SIM limits: at least name or phone needed, and SIM can't store extra fields     if (isSimAccountType(draft.accountType) && !hasSimNameOrPhone(draft)) {         val message = getApplication<Application>().getString(R.string.sim_name_or_phone_required)-        onResult?.invoke(false, message)+        onResult?.invoke(false, message, null)         return     }     val newContact = buildContactFromDraft(draft)     viewModelScope.launch {         val ok = withContext(Dispatchers.IO) { persistContact(newContact) }+        val savedId = when {+            !ok -> null+            isSimAccountType(newContact.accountType) -> findSavedSimContactId(newContact)+            else -> newContact.id.takeIf { it != 0L }+        }         if (ok) clearEditDraft()-        onResult?.invoke(ok, null)+        onResult?.invoke(ok, null, savedId)     } } 
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.ktindex 3687a6c99d..02b02e16b0 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelSim.kt@@ -32,6 +32,28 @@ internal suspend fun ContactViewModel.persistSimContact(     return ok } +/**+ * Id of the SIM contact just written from [contact], read from the post-save sync.+ * SIM ids hash the row's contents ([SimContactsDataSource.syntheticIdFor]), so every edit+ * changes them. Falls back to number-only, then name-only, since cards may truncate names.+ */+internal fun ContactViewModel.findSavedSimContactId(+    contact: com.vayunmathur.contacts.data.Contact+): Long? {+    val subId = contact.accountName?.toIntOrNull()?.toString()+    val name = simPersistName(contact)+    val number = contact.details.phoneNumbers.firstOrNull()?.number?.trim().orEmpty()+    val candidates = allContactsState.value.filter {+        isSimAccountType(it.accountType) && (subId == null || it.accountName == subId)+    }+    fun numberOf(c: com.vayunmathur.contacts.data.Contact) =+        c.details.phoneNumbers.firstOrNull()?.number?.trim().orEmpty()+    val match = candidates.firstOrNull { it.name.value.trim() == name && numberOf(it) == number }+        ?: candidates.firstOrNull { number.isNotEmpty() && numberOf(it) == number }+        ?: candidates.firstOrNull { name.isNotEmpty() && it.name.value.trim() == name }+    return match?.id+}+ internal fun ContactViewModel.simPersistName(     contact: com.vayunmathur.contacts.data.Contact ): String =