Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying for a contact's structured name returns null

Tags:

android

I have a list of Android contacts for which I'm trying to retrieve the given name, middle name and family name. I'm able to retrieve other pieces of information including email and phone number, but when I query the content resolver for the name parts of the contact I'm always getting null values in return (even though moveToNext() is executing, meaning that a record was retrieved from the system).

Relevant code:

String id = "Some ID";

// Perform a query to retrieve the contact's name parts
String[] nameProjection = new String[] {
        ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
        ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME,
        ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME
};
Cursor nameCursor = mContext.getContentResolver().query(
        ContactsContract.Data.CONTENT_URI,
        nameProjection,
        ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID
                + "=?", new String[] { id }, null);

// Retrieve the name parts
String firstName = "", middleName = "", lastName = "";
if(nameCursor.moveToNext()) {
    firstName = nameCursor.getString(nameCursor.getColumnIndex(
            ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
    middleName = nameCursor.getString(nameCursor.getColumnIndex(
            ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));
    lastName = nameCursor.getString(nameCursor.getColumnIndex(
            ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
}

After this piece of codes executes, the strings are null but no exception is thrown. I manually checked several contacts, all of whom had the given name, middle name and last name filled.

What am I doing wrong here?

like image 423
mittelmania Avatar asked Mar 19 '23 06:03

mittelmania


1 Answers

I discovered that I was missing the MIMETYPE condition in order to actually select the row from the aggregated table that contained the names.

I changed the nameCursor to:

Cursor nameCursor = mContext.getContentResolver().query(
        ContactsContract.Data.CONTENT_URI,
        nameProjection,
        ContactsContract.Data.MIMETYPE + " = '" + 
        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "' AND " + 
        ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID
                + " = ?", new String[] { id }, null);

And now it's working :)

like image 63
mittelmania Avatar answered Mar 26 '23 02:03

mittelmania