我正在使用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();

07-28 02:22
查看更多