问题
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:
Contacts
- each entry represents one contact, and groups together one or moreRawContacts
RawContacts
- each entry represents data about a contact that was synced in by someSyncAdapter
(e.g. Whatsapp, Google, Facebook, Viber), this groups multiple Data entriesData
- The actual data about a contact, emails, phones, etc. each line is a single piece of data that belongs to a singleRawContact
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_ID
s 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