【问题标题】:Android. Retrieve first name and last name from contact book by phone number安卓。通过电话号码从通讯录中检索名字和姓氏
【发布时间】:2021-11-30 06:22:58
【问题描述】:

我正在尝试通过电话号码获取通讯录中的名字和姓氏。 这是我的代码:

  Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
  Cursor cursor = cResolver.query(uri, null, null, null, null); 
  if(cursor != null && cursor.moveToFirst()) {
            int idColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            int firstNameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
            int lastNameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME);
            while (!cursor.isAfterLast()) {
                long id = cursor.getLong(idColumnIndex);
                contact = new  MyContact();
                contact.setId(id);
                contact.setFirstName(cursor.getString(firstNameIndex));
                contact.setLastName(cursor.getString(lastNameIndex));
            }
            cursor.close();
        }

firstNameIndexlastNameIndex 始终为 -1。我做错了什么?请帮帮我。

【问题讨论】:

    标签: android uri android-contentprovider android-contacts android-contentresolver


    【解决方案1】:

    PhoneLookup 是一种通过电话号码获取联系人数据的快捷方式,但它返回的光标仅限于 columns mentioned in the docs

    您可以看到有DISPLAY_NAME 可以访问,但没有GIVEN_NAMEFAMILY_NAME

    GIVEN_NAME & FAMILY_NAME 是存储在Data 表中的字段,这意味着您需要单独查询该表才能获取这些字段。

    因此,您可以使用从PhoneLookup 获得的联系人 ID 添加另一个查询(请注意,对于每个查找的电话,可能会返回多个联系人)。

    这是一个从联系人 ID 中获取名字/姓氏的示例方法:

    private void addNames(MyContact contact, long contactId) {
        String[] projection = new String[] {StructuredName.GIVEN_NAME, StructuredName.FAMILY_NAME};
        
        // filter to just StructuredName rows from the data table for the given contact
        String selection = Data.CONTACT_ID + "=" + contactID + " AND " + Data.MIMETYPE + "=" + StructuredName.CONTENT_ITEM_TYPE;
        
        Cursor cursor = getContentResolver().query(Data.CONTENT_URI, projection, selection, null, null);
        if (cursor.next()) {
            contact.setFirstName(cursor.getString(0));
            contact.setLastName(cursor.getString(1));
        }
        cursor.close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-10
      • 2012-12-10
      • 2012-10-27
      • 2010-12-30
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多