我想将我手机默认通讯录中的 1000 多个联系人加载并显示到listview
. 我的解决方案是两个步骤:
- 从我手机的默认通讯录中获取所有联系人并将它们全部存储到光标中。
- 在我
listview
的设置cursor adapter
中cursor
(使用代码:mylistview.setAdapter(curAdaptor))
好的,下面是我的代码: 1. 正如我上面所说。我查询并获取所有联系人的姓名、电话号码和公司。
public Cursor getContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "DISPLAY_NAME ASC");
String phoneNo = "";
String company = "";
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
//get ID & Name of the contact
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//get phone number
Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id},
null);
phoneNo = (pCur.moveToNext()) ? pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) : "Update";
//get company
String orgWhere = ContactsContract.Data.CONTACT_ID +
" = ? AND " +
ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{ id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query( ContactsContract.Data.CONTENT_URI,
null,
orgWhere,
orgWhereParams,
null);
company = (orgCur.moveToNext()) ? orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA)) : "Update";
//put new values into extras cursor
try {
extras.addRow(new String[] {id,
name,
phoneNo,
company });
} catch (Exception e) {
Log.e("ERROR CURSOR: ", e.getMessage());
}
orgCur.close();
pCur.close();
}
}
return extras;
}
第二步:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); extras = new MatrixCursor(new String[] { "_id", "contactName", "Phone", "Company" }); ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > (); ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null) .build()); Cursor cur = getContacts(); String[] from = new String[]{ "_id", "contactName", "phone", "company" }; int[] to = new int[] { R.id.contactId, R.id.contactName, R.id.phone, R.id.company }; try { curAdapter = new SimpleCursorAdapter( getApplicationContext(), R.layout.view_contact_entry, cur, from, to, 0); lv = (ListView) findViewById(android.R.id.list); lv.setAdapter(curAdapter); } catch (Exception e) { Log.e("ERROR: ", e.getMessage()); } //show all data onto listview lv = getListView();
}
好的,这就是我的问题:使用该解决方案,我花了大约 13 秒将所有联系人加载并显示到列表视图中。我想更快地加载和显示!我该怎么办。或者你能告诉我另一种解决问题的方法吗,比如:在android中使用惰性列表视图等......