Retrieving a Phone Number from Contacts Provider with ID, Android

前端 未结 2 898
梦毁少年i
梦毁少年i 2021-01-23 11:28

I am able to retrieve the contact ID, but then later I wish to separately retrieve the phone number based on the contact ID. The code below is returning a null result for the p

2条回答
  •  一个人的身影
    2021-01-23 11:57

    I have not been able to successfully retrieve code based on the Contact ID - but this post gave me a clue: Retrieving a phone number with ContactsContract in Android - function doesn't work

    I have altered my original code to query on DISPLAY_NAME instead and things are working now. Here is the method I am using to retrieve the phone number:

         private String retrieveContactNumber(String contactName) {
    
        Log.d(TAG, "Contact Name: " + contactName);
    
        Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
    
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ? AND " +
                        ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
    
                new String[]{contactName},
                null);
    
        if (cursorPhone.moveToFirst()) {
            contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }
    
        cursorPhone.close();
    
        Log.d(TAG, "Contact Phone Number: " + contactNumber);
    
        return contactNumber;
    }
    

提交回复
热议问题