0

私はAndroidアプリを作成しています。特定のグループから連絡先を削除したいのですが、連絡先を削除するのではなく、グループから削除するだけです。グループIDと連絡先IDがあります。これを行うためのクエリを教えてください。実装したいgroup_id=2 から contact_id=1 を削除するようなもの

4

2 に答える 2

1

連絡先は、ContactsContract.CommonDataKinds.GroupMembership レコードでグループにリンクされます。次のようなものを使用して、グループから連絡先を削除できます。

private void deleteContactFromGroup(long contactId, long groupId)
{
    ContentResolver cr = getContentResolver();
    String where = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=" + groupId + " AND "
            + ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID + "=?" + " AND "
            + ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
            + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";

    for (Long id : getRawContactIdsForContact(contactId))
    {
        try
        {
            cr.delete(ContactsContract.Data.CONTENT_URI, where,
                    new String[] { String.valueOf(id) });
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

private HashSet<Long> getRawContactIdsForContact(long contactId)
{
    HashSet<Long> ids = new HashSet<Long>();

    Cursor cursor = getContentResolver().query(RawContacts.CONTENT_URI,
              new String[]{RawContacts._ID},
              RawContacts.CONTACT_ID + "=?",
              new String[]{String.valueOf(contactId)}, null);

    if (cursor != null && cursor.moveToFirst())
    {
        do
        {
            ids.add(cursor.getLong(0));
        } while (cursor.moveToNext());
        cursor.close();
    }

    return ids;
}

削除を実行するときは、CONTACT_ID の代わりに RAW_CONTACT_ID を指定する必要があることに注意してください。したがって、指定された連絡先のすべての未加工の連絡先 ID を照会する必要があります。

また、アカウント データを考慮する必要がある場合もあります。その場合、連絡先 ID のクエリを次のように変更します。

Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon()
            .appendQueryParameter(RawContacts.ACCOUNT_NAME, accountName)
            .appendQueryParameter(RawContacts.ACCOUNT_TYPE, accountType).build();

Cursor cursor = getContentResolver().query(rawContactUri,
            new String[] { RawContacts._ID }, RawContacts.CONTACT_ID + "=?",
            new String[] { String.valueOf(contactId) }, null);
于 2012-09-20T07:11:15.927 に答える