0

I am developing an application, where I need to fetch the phone number from the contacts corresponding to the name provided. I have tried many codes but none of them seem to work.

Here is the code I'm currently using now

public static String getContactPhoneNumber(Context context, String contactName, int type) {
        String phoneNumber = null;

        String[] whereArgs = new String[] { contactName, String.valueOf(type) };

        Log.d(TAG, String.valueOf(contactName));

        Cursor cursor = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,
                ContactsContract.Contacts.DISPLAY_NAME + " = ? and "
                        + ContactsContract.CommonDataKinds.Phone.TYPE + " = ?", whereArgs, null);

        int phoneNumberIndex = cursor
                .getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);

        Log.d(TAG, String.valueOf(cursor.getCount()));

        if (cursor != null) {
            Log.v(TAG, "Cursor Not null");
            try {
                if (cursor.moveToNext()) {
                    Log.v(TAG, "Moved to first");
                    Log.v(TAG, "Cursor Moved to first and checking");
                    phoneNumber = cursor.getString(phoneNumberIndex);
                }
            } finally {
                Log.v(TAG, "In finally");
                cursor.close();
            }
        }

        Log.v(TAG, "Returning phone number");
        return phoneNumber;
    }

On passing Contact Name (say: John Doe) and type (2 which is int value for Mobile Type), the phone number returned is null even though the contact "John Doe" exists in my contact list.

Please help!!!

Joe Doyle
  • 6,363
  • 3
  • 42
  • 45
sarveshs
  • 68
  • 1
  • 2
  • 9

1 Answers1

0

Try this

instead of ContactsContract.CommonDataKinds.Phone.CONTENT_URI Pass ContactsContract.Contacts.CONTENT_URI parameter to query method.

android developer
  • 1,253
  • 2
  • 13
  • 43