Retrieving a phone number with ContactsContract in Android - function doesn't work

无人久伴 提交于 2019-11-30 10:14:30

To get the contact id in the first part, you should use:

ContactsContract.Data.CONTACT_ID

instead of:

ContactsContract.Contacts._ID

So the projection should be:

String[] projection = new String[] {
         ContactsContract.Data.CONTACT_ID,
         ContactsContract.CommonDataKinds.Event.CONTACT_ID,
         ContactsContract.CommonDataKinds.Event.START_DATE,
 };

And then of course get the correct row:

Long id = result.getLong(result.getColumnIndex(ContactsContract.Data.CONTACT_ID));

You are getting null because you have set your projection to null. The projection is basically the list of columns that you want returned e.g.

String[] projection = {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER};

Usually, when you find the contact, they may have a list of phone numbers, so you have to use another cursor to iterate through the phone numbers, e.g.

Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);    
while (phones.moveToNext()) 
{    
     phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
}

Hope this helps.

Your code for getContactPhone() works fine on my end. I tested by launching a contact picker, selecting a contact, then using the ID that was returned and passed that into your method.

So I suspect you are indeed passing in an invalid ID. Can you post the full stack trace for the null pointer exception?

Yes, lookup keys are available because _IDs are not guaranteed to stay the same since syncs and contact aggregation changes them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!