以下是我用于在Android中获取联系人的代码。
String[] projectionFields = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
CursorLoader cursorLoader = new CursorLoader(context,
ContactsContract.Contacts.CONTENT_URI,
projectionFields, // the columns to retrieve
SELECTION, // the selection criteria (none)
null, // the selection args (none)
null // the sort order (default)
);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor.moveToFirst()) {
int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
do {
String contactDisplayName = cursor.getString(nameIndex);
} while (cursor.moveToNext());
}
我也收到很多电子邮件联系人。我不想显示仅限电子邮件的联系人。我怎么能这样做呢?
答案 0 :(得分:1)
我从您的问题中了解到,您需要获取具有电话号码的联系人。如果是这种情况,您可以通过
检查联系人是否有电话号码ContentResolver contentResolver = getContentResolver();
ContentProviderClient mCProviderClient = contentResolver.acquireContentProviderClient(ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
Cursor cursor = mCProviderClient.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phones = mCProviderClient.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION_PHONE,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
}
mCProviderClient.close();
cursor.close();
}
hasPhoneNumber的值将是> 0,如果有联系人分配了电话号码。
答案 1 :(得分:0)