Android fetching group and its contact



On our recent project,there was a need to fetch groups and its respective contact from phone.So,in this post I am writing you the process on fetching group and its contact from phone.
Let’s first write a class which holds all the contact information and lets name it as Item

public class Item{
	public String name,id,phNo,phDisplayName,phType;
	public boolean isChecked =false;
}


Now let’s perform a simple content uri query to retrieve all the group from phone

    private ArrayList<Item> fetchGroups(){
    	ArrayList<Item> groupList = new ArrayList<Item>();
    	String[] projection = new String[]{ContactsContract.Groups._ID,ContactsContract.Groups.TITLE};
    	Cursor cursor = getContentResolver().query(ContactsContract.Groups.CONTENT_URI, 
    			projection, null, null, null);
    	ArrayList<String> groupTitle = new ArrayList<String>();
    	while(cursor.moveToNext()){
        		Item item = new Item();
        		item.id = cursor.getString(cursor.getColumnIndex(ContactsContract.Groups._ID));
        		String groupName =      cursor.getString(cursor.getColumnIndex(ContactsContract.Groups.TITLE));
        		
        	 if(groupName.contains("Group:"))
    		groupName = groupName.substring(groupName.indexOf("Group:")+"Group:".length()).trim();
    			
    		if(groupName.contains("Favorite_"))
    		groupName = "Favorite";
    			 
    		if(groupName.contains("Starred in Android") || groupName.contains("My Contacts"))
    		continue;
    			
    		if(groupTitle.contains(groupName)){
    		    for(Item group:groupList){
    			 if(group.name.equals(groupName)){
    				group.id += ","+item.id;
    				break;
    			 }
    		   }
    		}else{
    		  groupTitle.add(groupName);
    		  item.name = groupName;
    		 groupList.add(item);
    	     }
        		
    	}
    	
    	cursor.close();
    	Collections.sort(groupList,new Comparator<Item>() {
			public int compare(Item item1, Item item2) {
			return item2.name.compareTo(item1.name)<0
						?0:-1;
			}
		});
    	return groupList;
    }


The above code queries ContactsContract.Groups.CONTENT_URI for fetching out Group Id and Group Title as seen on projection. Here we are excluding group names Starred in Android and My Contacts . And further we are appending the group id having same group name.The reason for doing so is that,while running this query same group name appears multiple time but with different ids.We need to store these ids as we will query contact using these ids.Now our next process will be fetching contact within respective groups

    private void initContactList(){
    	groupList = new LinkedHashMap<Item,ArrayList<Item>>();
    	ArrayList<Item> groupsList = fetchGroups();
    		for(Item item:groupsList){
    			String[] ids = item.id.split(",");
    			ArrayList<Item> groupMembers =new ArrayList<Item>();
    			for(int i=0;i<ids.length;i++){
    				String groupId = ids[i];
    				groupMembers.addAll(fetchGroupMembers(groupId));
    			}	
    			item.name = item.name +" ("+groupMembers.size()+")";
    			groupList.put(item,groupMembers);
    		}
    }


The above method shows the process of querying with Group Id to fetch respective contacts under that group and the following code snippet illustrates on how to fetch the group members

   private ArrayList<Item> fetchGroupMembers(String groupId){
    	ArrayList<Item> groupMembers = new ArrayList<Item>();
    	String where =  CommonDataKinds.GroupMembership.GROUP_ROW_ID +"="+groupId
			       +" AND "
			       +CommonDataKinds.GroupMembership.MIMETYPE+"='"
			       +CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE+"'";
    	String[] projection = new String[]{GroupMembership.RAW_CONTACT_ID,Data.DISPLAY_NAME};
    	Cursor cursor = getContentResolver().query(Data.CONTENT_URI, projection, where,null,
    			Data.DISPLAY_NAME+" COLLATE LOCALIZED ASC");
    	while(cursor.moveToNext()){
    		Item item = new Item();
    		item.name = cursor.getString(cursor.getColumnIndex(Data.DISPLAY_NAME));
    		item.id = cursor.getString(cursor.getColumnIndex(GroupMembership.RAW_CONTACT_ID));
    		Cursor phoneFetchCursor = getContentResolver().query(Phone.CONTENT_URI,
    				new String[]{Phone.NUMBER,Phone.DISPLAY_NAME,Phone.TYPE},
    				Phone.CONTACT_ID+"="+item.id,null,null);
    		while(phoneFetchCursor.moveToNext()){
    			item.phNo = phoneFetchCursor.getString(phoneFetchCursor.getColumnIndex(Phone.NUMBER));
    			item.phDisplayName = phoneFetchCursor.getString(phoneFetchCursor.getColumnIndex(Phone.DISPLAY_NAME));
    			item.phType = phoneFetchCursor.getString(phoneFetchCursor.getColumnIndex(Phone.TYPE));
    		}
    		phoneFetchCursor.close();
    		groupMembers.add(item);
    	}	
    	cursor.close();
    	return groupMembers;
    }


In this manner we first query the Contact Id from the passed Group Id.And once queried Contact Id is received,we again query Phone.CONTENT_URI to get any further contact information.This is all you all have to do in order to fetch group and its contacts.I have gathered these resources from stackoverflow answers and if any of you have any better solution do update me.Till then happy coding ;)

About these ads

2 thoughts on “Android fetching group and its contact

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s