我正在实现一个AutoCompleteTextView,我需要所有联系人的姓名和电子邮件.
我发现这个代码段我异步运行,但是速度非常慢.
我发现这个代码段我异步运行,但是速度非常慢.
ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,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,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(); } } }
我正在执行一种内部查询,我认为这是问题.有没有办法调整它,使它更快?
解决方法
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); 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了解可以查询哪些列>使用投影只能获得真正需要的列,节省一些内存并增加查询性能>仅在while循环之前获取列索引一次