在尝试使用以下代码从Android检索联系人列表时,它会返回多个帐户,例如google / gmail,whatsapp和soma(激活了多少帐户取决于内容解析程序返回的那么多联系人副本!) 。 请帮我把它删除。
cursor1=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI ,null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +" ASC");
startManagingCursor(cursor1);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID,};
int[] to = {android.R.id.text1, android.R.id.text2};
listadapter = new SimpleCursorAdapter(getBaseContext(), android.R.layout.simple_list_item_2, cursor1, from, to);
setListAdapter(listadapter);
答案 0 :(得分:1)
Simpy尝试以下具有更多验证的代码,并检查它是否有电话号码。但是你的andorid设备的联系人应该妥善安排。
private void displayContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
}
pCur.close();
}
}
}
}
您可能还会在此处获得一些过滤帐户,例如使用以下代码过滤掉应用帐户的内容,该代码从电话联系人处获取应用联系人的内容:
Cursor c = getContentResolver().query(
RawContacts.CONTENT_URI,
new String[] { RawContacts.CONTACT_ID, RawContacts.DISPLAY_NAME_PRIMARY },
RawContacts.ACCOUNT_TYPE + "= ?",
new String[] { "com.whatsapp" },
null);
ArrayList<String> myWhatsappContacts = new ArrayList<String>();
int contactNameColumn = c.getColumnIndex(RawContacts.DISPLAY_NAME_PRIMARY);
while (c.moveToNext())
{
// You can also read RawContacts.CONTACT_ID to read the
// ContactsContract.Contacts table or any of the other related ones.
myWhatsappContacts.add(c.getString(contactNameColumn));
}