Android联系人--群组分组查询

时间:2022-09-16 13:00:15
Android联系人--群组分组查询

/**
	 * 当Groups.DELETED=0的时候, 是查询没有被删除的联系人分组
	 */
	public void getContactsGroups() {
		String[] RAW_PROJECTION = new String[] { ContactsContract.Groups._ID,
				ContactsContract.Groups.TITLE, };
		String RAW_CONTACTS_WHERE = ContactsContract.Groups.DELETED + " = ? ";
		Cursor cursor = getContentResolver().query(
				ContactsContract.Groups.CONTENT_URI, RAW_PROJECTION,
				RAW_CONTACTS_WHERE, new String[] { "" + 0 }, null);
		while (cursor.moveToNext()) {
			String id = cursor.getString(cursor.getColumnIndex("_id"));
			String title = cursor.getString(cursor.getColumnIndex("title"));
			Log.e("XZQ", id + "   " + title);
		}
		cursor.close();
	}

	/**
	 * 当Groups.DELETED=1的时候,是查询删除的分组
	 */
	public void getContactsGroups1() {
		String[] RAW_PROJECTION = new String[] { ContactsContract.Groups._ID,
				ContactsContract.Groups.TITLE };
		String RAW_CONTACTS_WHERE = ContactsContract.Groups.DELETED + " = ? ";
		Cursor cursor = getContentResolver().query(
				ContactsContract.Groups.CONTENT_URI, RAW_PROJECTION,
				RAW_CONTACTS_WHERE, new String[] { "" + 1 }, null);
		while (cursor.moveToNext()) {
			String id = cursor.getString(cursor.getColumnIndex("_id"));
			String title = cursor.getString(cursor.getColumnIndex("title"));
			Log.e("TAG", id + "   " + title);
		}
		cursor.close();
	}

	/**
	 * 默认情况下查询所有的分组
	 */
	public void getContactsGroups2() {
		Cursor cur = getContentResolver().query(Groups.CONTENT_URI, null, null,
				null, null);
		while (cur.moveToNext()) {
			int id = cur
					.getInt(cur.getColumnIndex(ContactsContract.Groups._ID));
			String title = cur.getString(cur
					.getColumnIndex(ContactsContract.Groups.TITLE));
			int count=getCountOfGroup(id);
			Log.e("MainActivity", id + "   " + title + "  " + count);
		}
		cur.close();
	}

	/**
	 * @param 群组ID
	 * @return 查询当前分组中有多少个联系人
	 */
	private int getCountOfGroup(int groupId) {
		String selection = ContactsContract.Data.MIMETYPE + "='"
				+ GroupMembership.CONTENT_ITEM_TYPE + "' AND "
				+ ContactsContract.Data.DATA1 + "=" + groupId;
		String[] colvalue = new String[] { ContactsContract.Data.RAW_CONTACT_ID };
		Cursor cursor = getContentResolver().query(
				ContactsContract.Data.CONTENT_URI, colvalue, selection, null,
				"data1 asc");
		int count = cursor.getCount();
		return count;
	}