Unable to get contacts with first and last name on ICS

I have this code to get the first and last name of contacts:

                uri = ContactsContract.Data.CONTENT_URI;
                Cursor curName = getContentResolver().query(uri, null, ContactsContract.Data.CONTACT_ID +" = "+ contactId, null, null);
                if (curName.getCount() > 0){
                    curName.moveToFirst();
                    String nameGiven = curName.getString(curName.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
                    String nameFamily = curName.getString(curName.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
                    log += nameGiven + ", " + nameFamily + ": ";
                }

I have only one contact, so I do not need a loop. On device 2.3.5, it works fine, returning the correct names. But on device 4.0.4, it returns null for both fields, but if you request a display name, it provides it correctly.

What could be the problem?

+5
source share
2 answers

Well, _ID in the data table and the contact table are two different things. So you should use raw_contacts_id instead of _id when querying a data table.

Let me throw a quick piece of code to get you started.

// projection
String[] projection = new String[] {ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME};

String where = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
String[] whereParameters = new String[]{this.contact_id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};

//Request
Cursor contacts = this.resolver.query(ContactsContract.Data.CONTENT_URI, projection, where, whereParameters, null);

//Iteration
if (contacts.moveToFirst()) { 
    //code here, E.g
                String nameGiven = contacts.getString(contacts.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
                String nameFamily = contacts.getString(contacts.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));

                //log += nameGiven + ", " + nameFamily + ": "; 

} 
contacts.close();
+2

, , ,

Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.CONTACT_ID + " = ?", new String[] {String.valueOf(contactId)}, null);
if (c.moveToFirst()){
    // get your code to get content on that cursor ex: c.getString(0)
}

, , .

0

All Articles