您的位置:首页 > 移动开发 > Android开发

android2.1取得通讯录联系人名字和电话号码

2011-03-20 09:29 363 查看
// 取得ContentResolver对象
ContentResolver cr = getContentResolver();
// 取得通讯录的光标
String orderBy = PhoneLookup.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, orderBy);

// 遍历通讯录
ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
for(int i=0; i<cursor.getCount() ;i++)
{
HashMap<String, Object> map = new HashMap<String, Object>();

cursor.moveToPosition(i);

// No.
map.put(COLUMN_ID, i + 1);

// 取得联系人名字
int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
String name = cursor.getString(nameFieldColumnIndex);
map.put(COLUMN_NAME, name);

// 取得联系人ID
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
null, null);

String number = "";
// 取得电话号码(可能存在多个号码)
for(int j = 0; j < phone.getCount(); j++)
{
phone.moveToPosition(j);
String strPhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (j > 0) {
number += " , ";
}
number += strPhoneNumber;
}
map.put(COLUMN_NUMBER, number);
Log.d(TAG, "number = " + number);
phone.close();

listItem.add(map);
}
cursor.close();

// 生成适配器的Item和动态数组对应的元素
SimpleAdapter listItemAdapter = new SimpleAdapter(this,
listItem,// 数据源
R.layout.list_item,// ListItem的XML实现
// 动态数组与ListItem对应的子项
new String[] { COLUMN_ID, COLUMN_NAME, COLUMN_NUMBER },
new int[] { R.id.TextView1, R.id.TextView2, R.id.TextView3 });
lv.setAdapter(listItemAdapter);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐