private boolean isGroupChecked(long groupId) {
   int count = mAdapter.getCount();
   for (int i = 0; i < count; i++) {
     GroupSelectionItem item = mAdapter.getItem(i);
     if (groupId == item.getGroupId()) {
       return item.isChecked();
     }
   }
   return false;
 }
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ListView list = (ListView) parent;
    int count = mAdapter.getCount();

    if (list.isItemChecked(count - 1)) {
      list.setItemChecked(count - 1, false);
      createNewGroup();
      return;
    }

    for (int i = 0; i < count; i++) {
      mAdapter.getItem(i).setChecked(list.isItemChecked(i));
    }

    // First remove the memberships that have been unchecked
    ArrayList<ValuesDelta> entries = mState.getMimeEntries(GroupMembership.CONTENT_ITEM_TYPE);
    if (entries != null) {
      for (ValuesDelta entry : entries) {
        if (!entry.isDelete()) {
          Long groupId = entry.getGroupRowId();
          if (groupId != null
              && groupId != mFavoritesGroupId
              && (groupId != mDefaultGroupId || mDefaultGroupVisible)
              && !isGroupChecked(groupId)) {
            entry.markDeleted();
          }
        }
      }
    }

    // Now add the newly selected items
    for (int i = 0; i < count; i++) {
      GroupSelectionItem item = mAdapter.getItem(i);
      long groupId = item.getGroupId();
      if (item.isChecked() && !hasMembership(groupId)) {
        ValuesDelta entry = RawContactModifier.insertChild(mState, mKind);
        entry.setGroupRowId(groupId);
      }
    }

    updateView();
  }