从Android联系人处获取联系人姓名和姓氏

时间:2012-10-21 06:04:03

标签: android android-contacts device

我正在构建一个需要从Android联系人中选择联系人的应用。我这样做,并在我的应用程序中使用以下代码来检索姓名和姓氏形式选择的联系人(在onActivityResult)。

Cursor namesc = getContentResolver().query( ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.CONTACT_ID + " = " + id,null, null);
if (namesc.moveToFirst()) {
String name = namesc.getString(namesc.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String family = namesc.getString(namesc
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String middle = namesc.getString(namesc
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));

它适用于HTC手机和其他一些手机,但在许多SE Xperia型号和一些三星设备中,它无法给我姓名和家人,并返回null。有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

以下是我使用的代码:

        String structuredNameWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
        String[] structuredNameWhereParams = new String[]{id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE}; 
        cursor = resolver.query(ContactsContract.Data.CONTENT_URI, null, structuredNameWhere, structuredNameWhereParams, null); 
        if (cursor.moveToFirst()) 
        { 
            String StructuredNameId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName._ID));
            String prefix = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.PREFIX));
            String givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
            String middleName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));
            String familyName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
            String suffix = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.SUFFIX));
        }

我真正看到的唯一区别是我将mime-type添加到where参数,而我检索的数据略有不同。