从android联系人中检索firstname和lastname会导致'1'和'null'

时间:2012-12-19 11:38:01

标签: android contactscontract

我正在使用以下代码从android联系人中检索名字和姓氏.DISPLAY_NAME给出了联系人的姓名,而firstname和lastname分别返回1和null。以下是代码。

ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
if (cur.getCount() > 0) {
    while (cur.moveToNext()) {
        String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?", new String[] { id }, null);
                while (pCur.moveToNext()) {
                    String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String firstname = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
                    String lastname = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
                    System.out.println("firstname and lastname" + firstname+ " "+lastname);
                    phoneNo = phoneNo.replaceAll("\\D", "");
                    names.add(name);
                    phnno.add(phoneNo);
                }
                pCur.close();
            }
        }           
    }

当我将行cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI)更改为cr.query(ContactsContract.Data.CONTENT_URI)时,我将日志更改为

enter image description here

建议非常感谢。谢谢提前

1 个答案:

答案 0 :(得分:9)

以下代码将帮助您获取名字和姓氏:

Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri dataUri = Uri.withAppendedPath(contactUri, Contacts.Data.CONTENT_DIRECTORY);
Cursor nameCursor = getActivity().getContentResolver().query(
        dataUri,
        null,
        Data.MIMETYPE+"=?",
        new String[]{ StructuredName.CONTENT_ITEM_TYPE },
        null);
           while (nameCursor.moveToNext())
            {

                String      firstName = nameCursor.getString(nameCursor.getColumnIndex(Data.DATA2));
                String  lastName = nameCursor.getString(nameCursor.getColumnIndex(Data.DATA3));

                Toast.makeText(getApplicationContext(), "First name"+firstName, Toast.LENGTH_LONG).show();
                Toast.makeText(getApplicationContext(), "Second name"+lastName, Toast.LENGTH_LONG).show();

                return new String [] {firstName , lastName};
            }

           nameCursor.close();