Reputation: 512
Below is the code I am using to fetch contacts in 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());
}
I am also getting a lot of email only contacts. I don't want to show email-only contacts. How can I go about this?
Upvotes: 0
Views: 85
Reputation: 2644
Please refer to this answer, it will allow only numbers and will also remove duplication.
Hope you find it helpful and your problem gets resolved.
Thanks.
Upvotes: 0
Reputation: 1215
I understand from your question that you need to get the contacts that has phone numbers. If this is the case, you can check if the contact has phone number by
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();
}
The value of hasPhoneNumber will be > 0, if there is a phone number assigned to the contact.
Upvotes: 1