如何提高数组列表的获取速度?



我正在使用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 个联系人。

相反,分页库将在用户滚动时获取较小的数量,从而擦除 600 个联系人的加载时间、600 个联系人的内存等......从而提高效率。

如果您担心速度,我会尝试使用 Set,尽管 ArrayList 中有 600+ 个联系人应该不是问题。当数据集达到数百万甚至更多时,这就会成为一个问题。我会尝试查看您的代码中的任何其他低效率。

就 Set 而言,两种最常见的 Java 数据结构是 HashSet 和 TreeSet。树集(如果要对集合进行排序)。HashSet 有点快,但你失去了排序。两者都有 O(1) 访问时间。

最新更新