I want to build a contact app which reads the contacts from the android device and show it in a list view. On clicking an item of list view a new activity will be opened where the details of the contact will be displayed. I have displayed the list view and am facing problems in getting the data from the simplecursoradapter. Can someone help me with the setOnItemClickListener() method?
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
read()
}
fun read()
{
var cursor : Cursor? =
contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null)
startManagingCursor(cursor)
var selected_columns = arrayOf(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID)
var to = intArrayOf(android.R.id.text1)
var simple : SimpleCursorAdapter = SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,cursor,selected_columns,to,0)
my_listview.adapter = simple
my_listview.setOnItemClickListener { parent, view, position, id ->
val intent = Intent(this, Contactdetails::class.java)
startActivity(intent)
}
}
}
You don't need to get data from SimpleCursorAdapter
. Just do it like so:
my_listview.setOnItemClickListener { parent, view, position, id ->
val intent = Intent(this, Contactdetails::class.java)
intent.putExtra("CONTACT_DATA" , cursor.getString(position))
startActivity(intent)
}