Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

android - Get a contact's groups?

I'm trying to make a many-to-many mapping of contacts to groups.

For example, if I have:

  • User 1, belongs to group 701, 702, 704
  • User 2, belongs to no groups
  • User 3, belongs to group 702

I'm hoping to get a relation that looks like this:

userID | groupID
1      | 701
1      | 702
1      | 704
3      | 702

I've tried this:

Cursor cursor = contentResolver.query(ContactsContract.Data.CONTENT_URI, null, new String[] {
    ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID,
    ContactsContract.CommonDataKinds.GroupMembership.GROUP_SOURCE_ID
}, null, null, null);

But that doesn't quite work. The GROUP_SOURCE_ID column returns weird numbers that aren't the ID of any groups. Sometimes it even returns 0 or a negative number.

I could construct a mapping of this by going through each group, and finding all contacts in that group, but that would take a lot of queries, and I'm trying to stay fast (apparently, just those few queries are quite slow!).

Can anyone tell me how I can get this contacts-to-groups mapping in one query?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
    Cursor dataCursor = getContentResolver().query(
            ContactsContract.Data.CONTENT_URI,
            new String[]{
                    ContactsContract.Data.CONTACT_ID,
                    ContactsContract.Data.DATA1
            },
            ContactsContract.Data.MIMETYPE + "=?",
            new String[]{ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE}, null
    );

By using this dataCursor you will get the contact_id and group_id of all contacts in the contact database.

    Cursor groupCursor = getContentResolver().query(
            ContactsContract.Groups.CONTENT_URI,
            new String[]{
                    ContactsContract.Groups._ID,
                    ContactsContract.Groups.TITLE
            }, null, null, null
    );

By using this groupCursor you will get the group_id and group_title of all groups in the contact database.

So if you want to get all groups associated with a contact_id the first get the dataCursor using suitable select statements. Using dataCursor you can get all the group_id associated with that contact_id. Now using groupCursor you can get the information about all groups associated with that specific contact.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...