Is there a way of getting all the phone numbers for all contacts without doing a separate query for each contact? (using Android 2.0+). It's really slow if you have over 100 contacts (unusable on low end phones), I wondered if I could do a more efficient query.
Currently I'm getting a cursor with all valid ContactsContract.Contacts.IN_VISIBLE_GROUP contacts then a separate query for each contact to get all their numbers.
Snippet from the get Contacts just geting name and lookup key:
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.LOOKUP_KEY};
Then each contact using the lookup key.
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
Uri res = ContactsContract.Contacts.l开发者_运维知识库ookupContact(contentResolver, lookupUri);
String[] projection = new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER};
...
Cursor phones = contentResolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, phoneProjection, selection, selectionArgs, sortOrder);
Check if the below code helps
public ArrayList<PhoneContactInfo> getAllPhoneContacts() {
Log.d("START","Getting all Contacts");
ArrayList<PhoneContactInfo> arrContacts = new ArrayList<PhoneContactInfo>();
PhoneContactInfo phoneContactInfo=null;
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor cursor = context.getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone._ID}, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
String contactNumber= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
phoneContactInfo = new PhoneContactInfo();
phoneContactInfo.setPhoneContactID(phoneContactID);
phoneContactInfo.setContactName(contactName);
phoneContactInfo.setContactNumber(contactNumber);
if (phoneContactInfo != null)
{
arrContacts.add(phoneContactInfo);
}
phoneContactInfo = null;
cursor.moveToNext();
}
cursor.close();
cursor = null;
Log.d("END","Got all Contacts");
return arrContacts;
}
精彩评论