2

我需要从所有 Android 联系人中获取信息:

  • 手机
  • 出生日期

如果联系人有两个或多个手机号码,则必须多次适合选择。

现在我ContentResolver.Query()用来获取所需的列,但需要不止一次的查询,而不是连接表。

如何从 Android 联系人中查询多个数据字段?

即我需要执行类似 SQL 查询的东西:

SELECT
    dName.Data2 as [firstName]
    , dName.Data3 as [lastName]
    , dPhone.Data1 as [cellPhone]
FROM
   raw_contacts
INNER JOIN data as dName on dName.RAW_CONTACT_ID = Contacts._ID and dName.MIME_TYPE =  ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE
INNER JOIN data as dPhone on dName.RAW_CONTACT_ID = Contacts._ID and dName.MIME_TYPE =  ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
4

1 回答 1

1

您提到的所有字段最终都存储在ContactsContract.Data表中,因此无需连接。您只需要查询 Data 表中的所有数据,同时选择您的特定 mimetypes(电话事件,即生日),完整的联系人姓名和联系人 ID,也为每个 mimetype 存储:

Map<Long, List<String>> contacts = new HashMap<Long, List<String>>();

String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3};
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Event.CONTENT_ITEM_TYPE + "')";
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);

while (cur != null && cur.moveToNext()) {
    long id = cur.getLong(0);
    String name = cur.getString(1); // full name
    String mime = cur.getString(2); // phone / birthday
    String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234

    String kind = "unknown";

    switch (mime) {
        case Phone.CONTENT_ITEM_TYPE: 
            kind = "phone"; 
            break;
        case Email.CONTENT_ITEM_TYPE: 
            Event = "birthday";
            break;
    }
    Log.d(TAG, "got " + id + ", " + name + ", " + kind + " - " + data);

    // add info to existing list if this contact-id was already found, or create a new list in case it's new
    List<String> infos;
    if (contacts.containsKey(id)) {
        infos = contacts.get(id);
    } else {
        infos = new ArrayList<String>();
        infos.add("name = " + name);
        contacts.put(id, infos);
    }
    infos.add(kind + " = " + data);
}
于 2017-08-15T08:23:40.170 回答