Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant get contacts given name and family name on ICS

I have this code for getting a contacts first name and family name:

                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 only have one contact so I dont need a loop. On an 2.3.5 device it works ok, returning the correct names. But on a 4.0.4 device it returns null for both fields, but if requesting the Display Name it provides it correctly.

What could be the problem?

like image 925
SnapDragon Avatar asked Nov 03 '22 05:11

SnapDragon


1 Answers

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

Let me throw in 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();
like image 139
Ben Max Rubinstein Avatar answered Nov 13 '22 02:11

Ben Max Rubinstein