从联系人列表获取名称和电子邮件非常慢 [英] Getting name and email from contact list is very slow
本文介绍了从联系人列表获取名称和电子邮件非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在实现一个AutoCompleteTextView,我需要所有我的联系人的名称和电子邮件。
我发现这个代码段,我是异步运行,但它是非常缓慢。
I'm implementing an AutoCompleteTextView and I need Name and E-Mail of all my contacts. I found this snippet that I'm running asynchronously but it's very slow.
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
while (emailCur.moveToNext()) {
String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
autoCompleteAdapter.add(name + " - " + email);
}
emailCur.close();
}
}
}
的内部查询,我认为这是问题。有没有办法调整它,使它更快?
I'm performing a sort of inner query and I think that's the problem. Is there a way to tune it and make it faster?
推荐答案
private static final String[] PROJECTION = new String[] {
ContactsContract.CommonDataKinds.Email.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA
};
...
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, null, null, null);
if (cursor != null) {
try {
final int contactIdIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID);
final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int emailIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
long contactId;
String displayName, address;
while (cursor.moveToNext()) {
contactId = cursor.getLong(contactIdIndex);
displayName = cursor.getString(displayNameIndex);
address = cursor.getString(emailIndex);
...
}
} finally {
cursor.close();
}
}
几个音符:
- 只需使用
ContactsContract.CommonDataKinds.Email.CONTENT_URI
即可获得所需的信息,请参阅 ContactsContract.CommonDataKinds.Email 了解您可以查询的列 - 使用投影仅获取您真正需要的列,可节省一些内存并提高查询性能
- 只在列表周期之前获取列索引
- use just
ContactsContract.CommonDataKinds.Email.CONTENT_URI
to get information you need, see ContactsContract.CommonDataKinds.Email for information what columns you can query - use projection to get only those columns you really need, you save some memory and increase query performance
- get column indexes only once, just before the while cycle
这篇关于从联系人列表获取名称和电子邮件非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文