views:

77

answers:

2

Hi,

I am trying to query contact information based on a phone number on android 1.6. This is the code I tried. But I get count equals to 0 in my cursor.

    String selection = "PHONE_NUMBERS_EQUAL(" + People.Phones.NUMBER + " , "   + phoneNumber + ")";
    Cursor cursor = mContext.getContentResolver().query(People.CONTENT_URI,
            new String[] {People._ID, People.NAME, People.Phones.NUMBER},
            selection, null, null);

Do you have any idea why it is not working?

Thank you.

A: 

Phone numbers are stored in their own table and need to be queried separately. To query the phone number table use the URI stored in the SDK variable Contacts.Phones.CONTENT_URI. Use a WHERE conditional to get the phone numbers for the specified contact.

if (Integer.parseInt(cur.getString(
        cur.getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {
    Cursor pCur = cr.query(
            Contacts.Phones.CONTENT_URI, 
            null, 
            Contacts.Phones.PERSON_ID +" = ?", 
            new String[]{id}, null);
    int i=0;
    int pCount = pCur.getCount();
    String[] phoneNum = new String[pCount];
    String[] phoneType = new String[pCount];
    while (pCur.moveToNext()) {
        phoneNum[i] = pCur.getString(
                           pCur.getColumnIndex(Contacts.Phones.NUMBER));
        phoneType[i] = pCur.getString(
                           pCur.getColumnIndex(Contacts.Phones.TYPE));
        i++;
    } 
}

Query the phones table and get a Cursor stored in pCur. Since the Android contacts database can store multiple phone numbers per contact we need to loop through the returned results. In addition to returning the phone number the query also returned the type of number (home, work, mobile, etc).

Also read this tutorial about Working With Android Contacts API For 1.6 and Before

Pentium10
A: 

You can specify a URI to and use a query to directly get a contact info by phone number..

Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(phoneNumber));

Cursor cursor = mContext.getContentResolver().query(contactUri, null, null, null, null);

The cursor returned by the code above should then contain the contact you are looking for and you can get the info out you need...

if(cursor.moveToFirst()){
    int personIDIndex = cursor.getColumnIndex(Contacts.Phones.PERSON_ID);
    //etc
}
Quintin Robinson