我希望能够从手机默认的通讯录中加载和显示1000多个联系人到listview中。我的解决方案分为两步:
- 获取手机默认通讯录中的所有联系人,并将它们存储到一个游标中。
- 在我的listview中,我使用游标适配器设置了游标(使用代码:mylistview.setAdapter(curAdaptor))。
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;
}
The second step:
@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中使用懒加载列表视图等...