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

后端 未结 3 1936
渐次进展
渐次进展 2021-01-01 04:08

I wrote the following function in order to retrieve one single phone number that belongs to the contact with id \"contactID\".

The function which is to retri

相关标签:
3条回答
  • 2021-01-01 04:25

    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.

    0 讨论(0)
  • 2021-01-01 04:27

    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.

    0 讨论(0)
  • 2021-01-01 04:34

    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));
    
    0 讨论(0)
提交回复
热议问题