Get a contact's groups? - android

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!

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.

A complete answer will be:
First the fetch the group cursor (same as the answer above)
Cursor groups_cursor= getContentResolver().query(
ContactsContract.Groups.CONTENT_URI,
new String[]{
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE
}, null, null, null
);
Store all the group_id and group_title in a groups HashMap using this code:
if(groups_cursor!=null){
while(groups_cursor.moveToNext()){
String group_title = groups_cursor.getString(1);
String id = groups_cursor.getString(0);
groups.put(id, group_title);
}
}
Then using the above answer's data_cursor, fetch contacts_ids and their group_ids.
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
);
Now using the dataCursor and the groups HashMap.
if(dataCursor!=null){
while(dataCursor.moveToNext()){
String id = dataCursor.getString(0);
String group_id= dataCursor.getString(1);
String groupTitle = groups.get(group_id);
Log.d(TAG, "groupTitle : " + groupTitle + " contact_id: " + id );
}
}

public static HashMap<String, String> getContactsForGroup(String groupID, Activity activity){
Cursor dataCursor = activity.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[]{ // PROJECTION
ContactsContract.Data.CONTACT_ID,
ContactsContract.Data.DISPLAY_NAME, // contact name
ContactsContract.Data.DATA1 // group
},
ContactsContract.Data.MIMETYPE + " = ? " + "AND " + // SELECTION
ContactsContract.Data.DATA1 + " = ? ", // set groupID
new String[]{ // SELECTION_ARGS
ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE,
groupID
},
null
);
dataCursor.moveToFirst();
HashMap<String, String> map = new HashMap<>();
while (dataCursor.moveToNext()) //
{
String s0 = dataCursor.getString(0); //contact_id
String s1 = dataCursor.getString(1); //contact_name
String s2 = dataCursor.getString(2); //group_id
Log.d("tag", "contact_id: " + s0 + " contact: " + s1 + " groupID: "+ s2);
map.put(s0, s1);
}
return map;
}

Related

How to get the first name of a contact in Android?

I'm trying to get the information of my contacts using ContactsContract and what I need to do, is to get only the first name of the contact. I used ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME but this get the name and the last name too, and I only want the name.
I tried using ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME but instead of getting the name, this get a number.
I have not found an exact way to get only the first name of the contact. Any idea?
You haven't shared your code, but it sounds like you're querying over table Phone.CONTENT_URI and trying to get a field via StructuredName.GIVEN_NAME.
That's not possible, as Phone.CONTENT_URI will only return phone rows, not StructuredName rows.
Here's code snippet to get all given-names from the Contacts DB:
String[] projection = new String[]{StructuredName.CONTACT_ID, StructuredName.GIVEN_NAME};
String selection = Data.MIMETYPE + "='" + StructuredName.CONTENT_ITEM_TYPE + "'";
Cursor c = getContentResolver().query(Data.CONTENT_URI, projection, selection, null, null);
DatabaseUtils.dumpCursor(c);
c.close();
UPDATE
Here's some sample code on how to query for multiple mimetypes in a single query.
In this example I created a mapping from to <given-name, phone> for each contact in the DB:
Map<Long, List<String>> contacts = new HashMap<Long, List<String>>();
String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, StructuredName.GIVEN_NAME, Phone.NUMBER };
// select all rows of type "name" or "phone"
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + StructuredName.CONTENT_ITEM_TYPE + "')";
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);
while (cur != null && cur.moveToNext()) {
long id = cur.getLong(0);
String name = cur.getString(1);
String mime = cur.getString(2); // type of row: phone / name
// get the existing <Given-name, Phone> list from the Map, or create a new one
List<String> infos;
if (contacts.containsKey(id)) {
infos = contacts.get(id);
} else {
infos = new ArrayList<String>(2);
contacts.put(id, infos);
}
// add either given-name or phone to the infos list
switch (mime) {
case Phone.CONTENT_ITEM_TYPE:
infos.set(1, cur.getString(4));
break;
case StructuredName.CONTENT_ITEM_TYPE:
infos.set(0, cur.getString(3));
break;
}
}

Android Contacts._ID != Data.CONTACT_ID

I'm running a query against CommonDataKinds.Phone.CONTENT_URI and I'm getting all the results that have a NOT NULL phone id.
pretty much the code is :
String[] projection2 = new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
String where2 = ContactsContract.CommonDataKinds.Phone._ID + " != ''" ;
Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection2, where2, null, null);
and then I iterate through each cursor result and getting the columns I want.
The code is :
if (phoneCursor.getCount() > 0) {
while (phoneCursor.moveToNext()) {
String contacts_id = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.Contacts._ID));
String phone_id = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
Log.i("phonecursor", "contacts_id= " + contacts_id + " phone_id " + phone_id
+ " contacts_name= " + contacts_name + " phone_name= " + phone_name
+ " Phone= " + phone );
}
phoneCursor.close();
}
What I dont get is why Phone.CONTACT_ID is different from the corresponding Contacts._ID from the same row...
Shouldn't both be the same? There are a lot of examples that use those exact columns to run queries. For example here and here if you check the Key pointers.
ContactsContract.Contacts._ID returns unique ID for a row
This is very good example
Image from Get Contact Emails By Content Provider - Android Example
ContactsContract.Contacts._ID returns unique ID for a row.
Now the output will vary based on which cursor you are querying ContactsContract.Contacts._ID.
If you query ContactsContract.Contacts._ID from ContactsContract.Contacts.CONTENT_URI , you will get ContactsContract.Contacts._ID and ContactsContract.CommonDataKinds.Phone.CONTACT_ID same.
But if you query ContactsContract.Contacts._ID from ContactsContract.CommonDataKinds.Phone.CONTENT_URI you will get ContactsContract.Contacts._ID and ContactsContract.CommonDataKinds.Phone.CONTACT_ID different as on each phone entry ContactsContract.Contacts._ID is incremented.
So if you want same _ID and Phone._ID then query from ContactsContract.Contacts.CONTENT_URI instead of ContactsContract.CommonDataKinds.Phone.CONTENT_URI

Problem in ContactsContract API android

i have an HTC legend.In its phone contacts it shows 4-5 contacts.But when i query it in my application it shows nearly 45 contacts.I think its gmail contacts.
String[] Projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts.STARRED};
Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, Projection, null, null, null);
I am getting all the details with photo as well in a listview. Now i need to get particular contact details like all his phone numbers,emails,photo etc.For this i am writing this query
final String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.IS_PRIMARY,
};
final Cursor phone = managedQuery(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
new String[]{contactId},
null);
> if(phone.moveToFirst()) {
> final int contactNumberColumnIndex =
> phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
> final int contactTypeColumnIndex =
> phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
i am getting all the details of the phone contact but not all other contacts.
i have read that all these details are stored in shared table(ContactsContract.Data.CONTENT_URI), but i am not getting exactly what to do go get this done.
Can someone help me figure out how to do this.
Thanks
You can do something like:
getContentResolver().query(
RawContactsEntity.CONTENT_URI,
// projection
new String[] {
BaseColumns._ID,
RawContactsEntity.MIMETYPE,
// DATA columns are interpreted according to MIMETYPE
// Project only union of data columns needed
RawContactsEntity.DATA1,
RawContactsEntity.DATA2,
RawContactsEntity.DATA3,
RawContactsEntity.DATA4,
RawContactsEntity.DATA7,
RawContactsEntity.DATA9,
RawContactsEntity.DATA10,
},
// selection
RawContactsEntity.DELETED + "<>1 AND " +
RawContactsEntity.MIMETYPE + " IN ('" +
StructuredName.CONTENT_ITEM_TYPE + "','" +
Email.CONTENT_ITEM_TYPE + "','" +
Phone.CONTENT_ITEM_TYPE + "','" +
StructuredPostal.CONTENT_ITEM_TYPE + "','" +
Organization.CONTENT_ITEM_TYPE + "')",
// selection params
null,
// sorting
null);
Next iterate through cursor, and first read MIME type:
final String mimeType = cursor.getString(cursor.getColumnIndex(
RawContactsEntity.MIMETYPE));
And depends on MIME type read corresponding data kind:
if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) {
readNameData(cursor);
} else if (Email.CONTENT_ITEM_TYPE.equals(mimeType)) {
addEmailData(cursor);
}
and so on.

Android get a cursor only with contacts that have an email listed >android 2.0

i have the following code to get contacts from content provider
String[] columns = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID,
ContactsContract.Contacts.PHOTO_ID };
Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,
columns, null, null, null);
and i use this one to get the emails for a specific contact by their id:
Cursor emails = getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = " + contact.getContactId(), null, null);
my current implementation passes every row in the cursor and aquires its emails and stores them in an arrayList of java objects.
what i was wondering if it was possible to do is just query the content provider and return a cursor of just contacts with ids/name etc that have an email address listed.
this way has a long waiting period for getting the contact list. i am using this list for a list adapter. if i can get only the contacts that have an email i can use a cursor adapter in my list.
Is something like this possible? how can i speed up the process?
#CapDroid
Fixed working code from DArkO's post:
ContentResolver cr = context.getContentResolver();
String[] PROJECTION = new String[] { ContactsContract.RawContacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID,
ContactsContract.CommonDataKinds.Email.DATA,
ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
String order = "CASE WHEN "
+ ContactsContract.Contacts.DISPLAY_NAME
+ " NOT LIKE '%#%' THEN 1 ELSE 2 END, "
+ ContactsContract.Contacts.DISPLAY_NAME
+ ", "
+ ContactsContract.CommonDataKinds.Email.DATA
+ " COLLATE NOCASE";
String filter = ContactsContract.CommonDataKinds.Email.DATA + " NOT LIKE ''";
Cursor cur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, filter, null, order);
Your cursor will have essential IDs as well as names and email addresses. The performance of this code is great because it requests few columns only.
I solved this one, here is how its done:
UPDATE
String[] PROJECTION = new String[] { ContactsContract.RawContacts._ID,
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_ID,
Email.DATA, ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
String order = " CASE WHEN " + ContactsContract.Contacts.DISPLAY_NAME
+ " NOT LIKE '%#%' THEN 1" + " ELSE 2 END, "
+ ContactsContract.Contacts.DISPLAY_NAME + " COLLATE NOCASE";
String filter = Email.DATA + " NOT LIKE '' ) GROUP BY ( " + Email.DATA;
return mContent.query(Email.CONTENT_URI,
PROJECTION, filter, null, order);

Android; I only have 2 contacts, yet I can obtain 5 from a query, why?

I have setup 2 test contacts in my emulator.
I'm running the following query, it should pick them both out, populate my domain object, and add to a list. The output at the bottom should therefore be 2, but it is 5, why is this? (cursor.getCount() is 5 instead of 2)
I have stepped through each iteration of the while loop and it is retreving the same contact multiple times, but with different values for POSTCODE, such as the phone number
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, null, null);
List<MeCercanaContact> contacts = new ArrayList<MeCercanaContact>();
if (cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
MyContact myContact = new MyContact();
String givenName = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
String postcode = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
myContact.setFirstName(givenName);
myContact.setLastName(postcode);
contacts.add(myContact);
}
}
System.out.println(contacts.size());
After API 21 We Write this Query for remove contact duplicacy.
String select = ContactsContract.Data.HAS_PHONE_NUMBER + " != 0 AND " +
ContactsContract.Data.MIMETYPE
+ " = " + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "
AND "+ ContactsContract.Data.RAW_CONTACT_ID + " = " +
ContactsContract.Data.NAME_RAW_CONTACT_ID;
Cursor cursor = mContent.query(ContactsContract.Data.CONTENT_URI, null, select,
null, null);
You are querying ContactsContract.Data, which is a generic container that holds a list of various contact details, such as phone numbers, postal codes etc.. You must filter the results for the rows whose ContactsContract.Data.MIMETYPE column equals StructuredPostal.CONTENT_ITEM_TYPE:
So change the query to:
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, ContacsContract.Data.MIMETYPE + "='" +
ContactsContract.StructuredPostal.CONTENT_ITEM_TYPE + "'", null);
See ContactsContract.Data
a contact that is registered to multiple groups will show up multiple times
if you query the Uri CONTENT_URI = ContactsContract.Data.CONTENT_URI
Add this to your SELECTION:
+ ContactsContract.Data.DATA1 + " = 1 " ; //show only contacts in group 1

Categories

Resources