I have an application which get contact's list and contact details. All data is displayed in two fragments. The main fragment is contain contact list. Where I click on some item it returns contact's id. If I choose first item of list - everything is correct, but if a choose another contact it returns wrong 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)
})
}
}
This is listing of 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"
}
}
Solution: I forgot add ContactsContract.CommonDataKinds.Phone.CONTACT_ID into projection. After adding it, I get right id's and all details was displayed correctly.
P.S. Also I changed constant CONTACT_ID_INDEX from 0 to 1