我正在使用Arraylist
来获取我的应用程序中的所有可用联系人。这是没有效率的,因为Arraylist
需要很长时间才能获取和填充Listview
,因为几乎有600+ contacts
。
我正在寻找一种具有更好性能的替代方法。
虽然我搜索了其他相关问题,但我找不到方便的问题。
这是我的java代码:
private List<String> getContactList() {
List<String> stringList=new ArrayList<>();
ContentResolver cr = context.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME)
);
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null
);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.v("Data : ",""+id+" "+name+" "+phoneNo);
stringList.add(id);
stringList.add(name);
stringList.add(phoneNo);
}
pCur.close();
}
}
}
if(cur!=null){
cur.close();
}
return stringList;
}
您的查询效率低下,您目前正在对每个联系人执行查询,这非常慢,您可以使用一个大查询(这非常快)来完成所有操作:
String[] projection = new String[] { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor c = cr.query(Phone.CONTENT_URI, projection, null, null, null);
while (c.moveToNext()) {
long contactId = c.getLong(0);
String name = c.getString(1);
String phone = c.getString(2);
Log.i("Phones", "got contact phone: " + contactId + " - " + name + " - " + phone);
}
c.close();
您可以考虑使用Paging
库:https://developer.android.com/topic/libraries/architecture/paging/
它的设计理念是列表只显示一定数量的项目,因此实际上没有必要以比它可能显示的方式更多的方式加载方式。例如,ListView可能只显示10个联系人,因此不需要获取600个联系人。
相反,Paging库将在用户滚动时获取较小的数量,从而消除600个联系人的加载时间,600个联系人的内存等等...从而使其更有效。
如果您担心速度,我会尝试使用Set,尽管ArrayList中有600多个联系人应该不会有问题。当数据集数百万甚至更多时,它就成了问题。我会尝试查看代码中的任何其他低效问题。
就Set而言,两个最常见的Java数据结构是HashSet和TreeSet。 TreeSet如果要对要订购的集合。 HashSet有点快,但你输掉了订单。两者都有O(1)访问时间。