@Override public AccountSet loadInBackground() { Context context = getContext(); final AccountTypeManager accountTypes = AccountTypeManager.getInstance(context); final ContentResolver resolver = context.getContentResolver(); final AccountSet accounts = new AccountSet(); for (AccountWithDataSet account : accountTypes.getAccounts(false)) { final AccountType accountType = accountTypes.getAccountTypeForAccount(account); if (accountType.isExtension() && !account.hasData(context)) { // Extension with no data -- skip. continue; } AccountDisplay accountDisplay = new AccountDisplay(resolver, account.name, account.type, account.dataSet); final Uri.Builder groupsUri = Groups.CONTENT_URI .buildUpon() .appendQueryParameter(Groups.ACCOUNT_NAME, account.name) .appendQueryParameter(Groups.ACCOUNT_TYPE, account.type); if (account.dataSet != null) { groupsUri.appendQueryParameter(Groups.DATA_SET, account.dataSet).build(); } final Cursor cursor = resolver.query(groupsUri.build(), null, null, null, null); if (cursor == null) { continue; } android.content.EntityIterator iterator = ContactsContract.Groups.newEntityIterator(cursor); try { boolean hasGroups = false; // Create entries for each known group while (iterator.hasNext()) { final ContentValues values = iterator.next().getEntityValues(); final GroupDelta group = GroupDelta.fromBefore(values); accountDisplay.addGroup(group); hasGroups = true; } // Create single entry handling ungrouped status accountDisplay.mUngrouped = GroupDelta.fromSettings( resolver, account.name, account.type, account.dataSet, hasGroups); accountDisplay.addGroup(accountDisplay.mUngrouped); } finally { iterator.close(); } accounts.add(accountDisplay); } return accounts; }
/** * Create an {@link EntitySet} based on {@link Contacts} specified by the given query parameters. * This closes the {@link EntityIterator} when finished, so it doesn't subscribe to updates. */ public static EntitySet fromQuery( ContentResolver resolver, String selection, String[] selectionArgs, String sortOrder) { EntityIterator iterator = null; final EntitySet state = new EntitySet(); try { // Perform background query to pull contact details iterator = resolver.queryEntities(RawContacts.CONTENT_URI, selection, selectionArgs, sortOrder); while (iterator.hasNext()) { // Read all contacts into local deltas to prepare for edits final Entity before = iterator.next(); final EntityDelta entity = EntityDelta.fromBefore(before); state.add(entity); } } catch (RemoteException e) { throw new IllegalStateException("Problem querying contact details", e); } finally { if (iterator != null) { iterator.close(); } } return state; }