Search code examples
androidcursorcontactscontractphone-number

Contact's ID from number


I can find the number of the contact from her id. The following snippet prints a number on the screen.

Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            CONTACT_PROJECTION,ContactsContract.CommonDataKinds.Phone._ID +" = 4627",
            null, null);
    phones.moveToNext();
    String phoneNumber = phones.getString(
            phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    Toast.makeText(getBaseContext(), phoneNumber, Toast.LENGTH_LONG).show();

However, if I try to find her id from her number,

Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            CONTACT_PROJECTION,ContactsContract.CommonDataKinds.Phone._ID +" = 4627",
            null, null);
    phones.moveToNext();
    String phoneNumber = phones.getString(
            phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            //Now I got a valid phone number


            //using that number to find the id
    Cursor ids = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            CONTACT_PROJECTION,ContactsContract.CommonDataKinds.Phone.NUMBER +" = "+ phoneNumber,
            null, null);
    ids.moveToNext();
    String id = ids.getString(
            ids.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
    Toast.makeText(getBaseContext(), id, Toast.LENGTH_LONG).show();

I get the following error.

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

The projection I use is as follows:

private static final String[] CONTACT_PROJECTION = new String[] {
    ContactsContract.CommonDataKinds.Phone.NUMBER,
    ContactsContract.CommonDataKinds.Phone._ID
};

The second cursor is empty even if I know there is such an entry in the contacts. What am I doing wrong?


Solution

  • Don't know why, but PhoneLookup worked for me. For those who have the same problem, here is my code.

    Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode("aNumber"));
    Cursor phones = getContentResolver().query(contactUri , PEOPLE_PROJECTION, null, null, null);
    //here, the cursor keeps the wanted contact
    
    ...
    
    private static final String[] PEOPLE_PROJECTION = new String[] {
        ContactsContract.PhoneLookup._ID
    };