我正在尝试在应用程序内的列表视图中显示用户手机中的联系人列表。我可以获取联系人,但有些联系人会有多个手机号码,所以我想多次向该人展示。
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String name, number = "";
String id;
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id },
null);
while (pCur.moveToNext()) {
number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
Log.i("name ", name + " ");
Log.i("number ", number + " ");
c.moveToNext();
想要向用户显示他拥有的号码的次数。我是否能够根据只有10位数的手机号码进行短名单?
Example
Name: John Doe
Number 1: xxxxxxxxx
Number 2: xxxxxxxxx
Name: Sarah
Number 1: xxxxxxxxx
这应该返回三个列表项作为跟随
John Doe xxxxxxxxx
John Doe xxxxxxxxx
Sarah xxxxxxxxx
答案 0 :(得分:2)
您可以尝试这样的事情
List<PhoneItem> phoneNoList = new ArrayList<PhoneItem();
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String name, number = "";
String id;
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id },
null);
while (pCur.moveToNext()) {
phoneNoList.add(new PhoneItem(name, pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))));
}
}
c.moveToNext();
}
for (PhoneItem row : phoneNoList) {
Log.i("name", row.name);
Log.i("number", row.number+"");
}
[...]
private class PhoneItem {
String name;
String phone;
public PhoneItem(String name, String phone) {
this.name = name;
this.phone = phone;
}
}
答案 1 :(得分:1)
以下代码将使用电话号码获取所有联系人。可能有重复,因为相同的联系人可能属于不同的组。你必须循环并消除重复。
String[] projection = new String[]{ ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,};
String selection = ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "=?" ;
String[] selectionArgs = new String[] {"1"};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
selection,
selectionArgs,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ ", " + ContactsContract.CommonDataKinds.Phone.NUMBER);