光标 returns 错误的联系人 ID

Cursor returns wrong contact id

我有一个获取联系人列表和详细联系信息的应用程序。所有数据都显示在两个片段中。主要片段包含联系人列表。在我点击某个项目的地方它 returns 联系人的 ID。如果我选择列表的第一项 - 一切都是正确的,但如果选择另一个联系它 returns 错误的 ID。

override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        (parent?.adapter as? CursorAdapter)?.cursor?.apply {
            moveToPosition(position)
            val contactId = getLong(CONTACT_ID_INDEX)

            startActivity(Intent(activity, DetailedActivity::class.java).also {
                it.putExtra(SELECTED_CONTACT_INDEX, contactId)
            })
        }
    } 

这是 ContactLoader 的清单 class:

class ContactLoader(private val context: FragmentActivity?) : LoaderManager.LoaderCallbacks<Cursor> {

    private var cursorAdapter: SimpleCursorAdapter? = null

    private val fromColumns: Array<String> = arrayOf(
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
        ContactsContract.CommonDataKinds.Phone.NUMBER
    )

    private val toIds = intArrayOf(
        R.id.contact_name,
        R.id.contact_phone
    )

    private val projection: Array<out String> = arrayOf(
        ContactsContract.CommonDataKinds.Phone._ID,
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
        ContactsContract.CommonDataKinds.Phone.NUMBER
    )

    fun initContactLoader() {

        cursorAdapter = context?.let {
            LoaderManager.getInstance(it).initLoader(0, null, this)

            SimpleCursorAdapter(
                it,
                R.layout.contact_list_item,
                null,
                fromColumns, toIds,
                0
            )
        }
    }

    fun getAdapter() = cursorAdapter

    override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> = context?.let {
        CursorLoader(
            it,
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            projection,
            null,
            null,
            sortOrder
        )
    } ?: throw IllegalStateException()

    override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) {
        cursorAdapter?.swapCursor(data)
    }

    override fun onLoaderReset(loader: Loader<Cursor>) {
        cursorAdapter?.swapCursor(null)
    }

    companion object {
        private const val sortOrder: String =
            "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY} ASC"
    }

}

解决方法: 我忘了把ContactsContract.CommonDataKinds.Phone.CONTACT_ID加到投影里了。添加后,我获得了正确的 ID,并且所有详细信息都正确显示。

P.S。我也将常量 CONTACT_ID_INDEX 从 0 更改为 1