联系人列表中有多少联系人?

5

我如何知道联系人列表中有多少个联系人?我已经得到了联系人数量,但一个人可以有多个联系人,我想在查找联系人列表中的总联系人数时考虑到这一点。

4个回答

11

查找所有联系人电话号码的数量

Cursor cursor =  managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

int count = cursor.getCount();

要查找特定RawContactID(将联系人ID值传递给rawContactId)的所有电话号码数量。

Cursor cursor =  managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID + " = " + rawContactId, null, null);

    int count = cursor.getCount();

通过以下查询可以确定在ContactsListActivity中显示的联系人数量。

Cursor cursor =  managedQuery(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

int count = cursor.getCount();

然而,如果一个人在多个账户下被输入,则以上查询仅获取单个实例,因为ContactsContract.Contacts会合并所有这样的联系人。

Cursor cursor =  managedQuery(RawContacts.CONTENT_URI, null, null, null, null);

int count = cursor.getCount();

可以在http://developer.android.com/resources/articles/contacts.html找到ContactsContract.Contacts和RawContacts之间的关系。

希望这能解决您的疑问!


抱歉,但是它不起作用。它也会给我那些没有联系电话的内容,只有电子邮件地址的内容。所以我们能否获得存储在联系人列表中的总电话号码数量? - nimi
这段代码将返回所有联系人。我无法得到确切的要求。我回答了以下问题:“如何确定联系人列表中有多少联系人?”您需要找到所有联系人的电话号码总数吗?如果是这种情况,我会编辑我的答案。 - Manish Khot

1

我们知道managedQuery已经被弃用,我们可以这样完成这个任务

ContentResolver contentResolver = getContentResolver();
            Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
            int contactNewCount = cursor.getCount();
            cursor.close();

1

虽然这是一个非常老的帖子,但如果你想要统计有电话号码的联系人,你可以使用以下方法:

Cursor cursor =  managedQuery(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts.HAS_PHONE_NUMBER, null, null);
int count = cursor.getCount();

当然,现在managedQuery已经过时了,但在紧急情况下这可能会有所帮助 :)

0
如果有人仍需要答案:
`managedQuery` 已经被弃用,所以我们将使用 `getContentResolver()` 中的 `query` 替代它。
int contactCount = 0;

Cursor cursor = getContentResolver().query(android.provider.ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null) {
    contactCount = cursor.getCount();
    cursor.close();
}

注意:此答案已在Android 10、11和12上进行了测试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接