I have a problem in querying phonebook contacts. What I need to do is get a list of contacts that have both phone and email entered or are of a specific type.
Basically like this:
public static final String SELECTION =
"("+ContactsContract.Contacts.HAS_PHONE_NUMBER +"='1') OR " + RawContacts.ACCOUNT_TYPE + "='" + Constants.ACCOUNT_TYPE + "'";
Now, the problem is, that RawContacts.ACCOUNT_TYPE
does not exist in the ContactsContract.Contacts.CONTENT_URI
, which I use with my query. I'm guessing I'd need to join another table, but have no idea how to do so.
Can anyone help me here, please?
The best way to read a raw contact along with all the data associated with it is by using the ContactsContract.RawContacts.Entity
directory. If the raw contact has data rows, the Entity cursor will contain a row for each data row. If the raw contact has no data rows, the cursor will still contain one row with the raw contact-level information.
Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
Uri entityUri = Uri.withAppendedPath(rawContactUri, Entity.CONTENT_DIRECTORY);
Cursor c = getContentResolver().query(entityUri,
new String[]{RawContacts.SOURCE_ID, Entity.DATA_ID, Entity.MIMETYPE, Entity.DATA1},
null, null, null);
try {
while (c.moveToNext()) {
String sourceId = c.getString(0);
if (!c.isNull(1)) {
String mimeType = c.getString(2);
String data = c.getString(3);
//decide here based on mimeType, see comment later
}
}
} finally {
c.close();
}
You will have to filter the result based on the mimeType
For example, if the mimeType is Phone.CONTENT_ITEM_TYPE
, then the column DATA1
stores the phone number, but if the data kind is Email.CONTENT_ITEM_TYPE
, then DATA1
stores the email address.
This way you won't have to use HAS_PHONE_NUMBER
as you will directly iterate trough the items.