ContactsContract select records by phone number

风格不统一 提交于 2019-12-24 07:16:02

问题


I can select all contacts using the query below

    cr = mActivity.getContentResolver();
    String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " > 0";
    String orderBy = ContactsContract.Contacts.DISPLAY_NAME + " ASC ";
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, selection, null, orderBy);

However, I have a phone number list and I want to create this query like

String selection = ContactsContract.Contacts.PhoneNumber_or_something_else  in (MyPhoneNumberArray)

Is that possible to do this?

A worst-case scenario, I can remove the related item using do while after I create my cursor, but, as far as I know, I cannot remove any record from the cursor.


回答1:


The Contacts DB is organized in three main tables:

  1. Contacts - each entry represents one contact, and groups together one or more RawContacts
  2. RawContacts - each entry represents data about a contact that was synced in by some SyncAdapter (e.g. Whatsapp, Google, Facebook, Viber), this groups multiple Data entries
  3. Data - The actual data about a contact, emails, phones, etc. each line is a single piece of data that belongs to a single RawContact

All phone numbers in the Contacts DB are in the Data table, so that's what you need to query, you can get the list of CONTACT_IDs from that query and use it to get general info about contacts if you need.

String[] phonesList = new String[] { "+121212345" }; // will work better if all phones in this list are in e164 format

String[] projection = { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER, Phone.NORMALIZED_NUMBER };
String selection = Phone.NUMBER + " IN ('" + TextUtils.join("','", phonesList) + "') OR " + 
                   Phone.NORMALIZED_NUMBER + " IN ('" + TextUtils.join("','", phonesList) + "')";
Cursor cur = cr.query(Phone.CONTENT_URI, projection, selection, null, null);

while (cur != null && cur.moveToNext()) {
    long id = cur.getLong(0);
    String name = cur.getString(1);
    String phone = cur.getString(2);
    Log.d(TAG, "got " + id + ", " + name + ", " + phone;
}


来源:https://stackoverflow.com/questions/50077278/contactscontract-select-records-by-phone-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!