I am trying to develop an app which will read the contacts from the phone and display the names of the contacts in a listview. On clicking an item of a listview the details of the contact such as name,email address and phone number will be displayed in another activity. I am able to display the name and phone number but cannot display the email address. Can anyone help to make necessary changes to read the email address and display it in the contact details?
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)
simple = 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 ->
//Log.i("Details","Opened")
val name = cursor?.getString(cursor?.getColumnIndex(selected_columns[0]))
val phone = cursor?.getString(cursor?.getColumnIndex(selected_columns[1]))
val intent = Intent(this, Contactdetails::class.java)
intent.putExtra("personname",name)
intent.putExtra("personnumber",phone)
startActivity(intent)
}
#Edited and added the function to get emails
fun getemails(context:Context):ArrayList<String>{
val emails = ArrayList<String>()
var mEmail = ""
val mEmailCursor: Cursor? = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Email.CONTACT_ID,null, null);
if (mEmailCursor!!.getCount() > 0) {
while (mEmailCursor.moveToNext()) {
mEmail = mEmailCursor.getString(mEmailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)).trim();
if (mEmail != null) {
emails.add(mEmail);
}
}
}
mEmailCursor.close();
return emails;
}
Using this code to find all emails link with your contact just pass contact_id
public ArrayList<String> getEmail(Context context, String contact_id) {
ArrayList<String> emails = new ArrayList<>();
String mEmail = "";
Cursor mEmailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?", new String[]{contact_id}, null);
if (mEmailCursor.getCount() > 0) {
while (mEmailCursor.moveToNext()) {
mEmail = mEmailCursor.getString(mEmailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)).trim();
if (mEmail != null) {
emails.add(mEmail);
}
}
}
mEmailCursor.close();
return emails;
}