1

I am trying to write a method that determines if a contact has at least one phone number, at the moment I have this:

public boolean hasPhone() {
 Cursor phones = this.map.getContentResolver().query(
  ContactsContract.Contacts.CONTENT_URI,
  null,
  ContactsContract.Contacts._ID + "=" + this.contactId,
  null,
  null
 );
 boolean has = false;
 if(phones.moveToFirst()) {
  do {        
    if(Integer.parseInt(phones.getString(phones.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
      has = true;
      break;
    }
  } while(phones.moveToNext());
 }
 return has;
}

the method always returns false, even though I know the contact in question has a phone number. Also I know the contactId is correct as I also use it to get the postal address, etc.

Any help would be greatly appreciated, as I am about to tear my hair out :p

Thanks.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
Kanodi
  • 11
  • 2
  • I'd suggest to use the debugger to evaluate where is the bug. Does phones.moveToFirst return true? What about phones.getColumnIndex? – Guido Aug 08 '10 at 09:43
  • Hi Guido, thanks for the reply. No moveToFirst does not return true. Does this mean the contact does not exist with that id? – Kanodi Aug 08 '10 at 09:46
  • According to [this](http://developer.android.com/reference/android/database/Cursor.html#moveToFirst(\)), it returns false if the cursor is empty. So, your `query(...)` isn't returning any rows. – Stephen Aug 08 '10 at 09:50
  • Hmm okay thanks, it is strange though, as I have a very similar method that returns the contacts name which works fine – Kanodi Aug 08 '10 at 10:09
  • I decided to output all the phone numbers to the log with there CONTACT_ID, and none of the CONTACT_ID's match those of the actual contacts on the phone. I am really unsure why this is, as I can fetch the contacts addresses with this id. Any ideas? – Kanodi Aug 08 '10 at 14:48

1 Answers1

1

Try this. Replace the following line

ContactsContract.Contacts._ID + "=" + this.contactId,

with this line

ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + this.contactId,

See if that works.

Camille Sévigny
  • 5,104
  • 4
  • 38
  • 61