1.最简洁的方法
使用类
android.provider.ContactsContract.CommonDataKinds.Phone;
代码如下:
<span style="font-size:18px;"> Cursor c = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null,null);
startManagingCursor(c);
ListAdapter adapter=new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
c,
new String[]{Phone.DISPLAY_NAME,Phone.NUMBER},
new int[]{android.R.id.text1,android.R.id.text2}); </span>
然后就可以使用ListView显示姓名和电话号码了。
注意:
1.如果一个人有两个电话,则分别显示。
2.如果有两个相同的人,也会分别显示,不会显示一个人的。
运行结果:
2.一般方法
使用类<span style="font-size:18px;">android.provider.ContactsContract.Contacts </span>
代码如下:<span style="font-size:18px;">Map<String,String> contacts;
List<Map<String,String>> list=new ArrayList<Map<String,String>>();
int nameIndex=-1;
ContentResolver cr=getContentResolver();
Cursor cur=cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null,null);
while(cur.moveToNext()){
number="";
//得到名字
nameIndex=cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
name=cur.getString(nameIndex);
//得到电话号码
String contactId = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID)); // 获取联系人的ID号,在SQLite中的数据库ID
Cursor phone = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
+ contactId, null, null);
while (phone.moveToNext()) {
String strPhoneNumber = phone.getString(
phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); // 手机号码字段联系人可能不止一个
number += strPhoneNumber+"\n";
}
contacts=new HashMap<String,String>();
//放入Map
contacts.put("name", name);
contacts.put("number", number);
list.add(contacts);
}
cur.close(); </span>
得到名字和电话号码,放入Map中,然后再钭Map放入List中。
之后就可以使用ListView显示名字和电话号码:
部分代码如下:
<span style="font-size:18px;">SimpleAdapter 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});
listView.setAdapter(adapter); </span>
注意:
1.若一个姓名下有多个电话号码,则只显示一个姓名,多个号码。
2.若有多个同名的,还是显示多个姓名。
结果截图:
![](http://hi.csdn.net/attachment/201110/3/0_1317643232pLmR.gif)