Android2.0之后的版本中,对通讯录列表contact中的内容做了一些改进,number这个属性被移动到了另一地方(Uri: ContactsContract.CommonDataKinds.Phone.CONTENT_URI)。当我们学习关于Android的教程或在网上查看这方面的资料时,提供的程序大部分如下:
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
startManagingCursor(cur);
ListAdapter adapter = new SimpleCursorAdapter(
this,
android.R.layout.expandable_list_content,
cur,
new String[]{PhoneLookup.DISPLAY_NAME,PhoneLookup.NUMBER},
new int[]{android.R.id.text1,android.R.id.text2});
listView.setAdapter(adapter);
......
然而,每次运行这段程序之后都会报错,提示source not found, Caused by: java.lang.IllegalArgumentException: column 'number' does not exist。如果我们将查询列PhoneLookup.NUMBER替换为别的列信息或删除,则程序可以正常运行。因此,为了能够显示电话号码信息,我们需要到ContactsContract.CommonDataKinds.Phone.CONTENT_URI中获取号码信息,如下:
ArrayList list = new ArrayList<Map<String, String>>(); //记录电话列表信息
while (cur.moveToNext()) {
Map<String, String> map = new HashMap<String, String>();
long id = cur.getLong(cur.getColumnIndex("_id"));
StringBuilder buf = new StringBuilder(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
buf.append("=").append(id);
Cursor pcur = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, buf.toString(), null, null);
//移动pcur游标,查找所有的电话列表
//......
pcur.close();
//将联系人姓名和电话信息组成键值对放入map中,然后添加到list中
}
cur.close();
ListAdapter adapter = new SimpleAdapter(
this,
list,
android.R.layout.simple_list_item_2,
new String[]{ NAME, NUMBER },
new int[]{ android.R.id.text1, android.R.id.text2 });
......