Example usage for android.provider ContactsContract AUTHORITY

List of usage examples for android.provider ContactsContract AUTHORITY

Introduction

In this page you can find the example usage for android.provider ContactsContract AUTHORITY.

Prototype

String AUTHORITY

To view the source code for android.provider ContactsContract AUTHORITY.

Click Source Link

Document

The authority for the contacts provider

Usage

From source file:com.openerp.base.res.Res_PartnerSyncHelper.java

private void addContact(Context context, Account account, String partner_id, String name, String mail,
        String number, String mobile, String website, String street, String street2, String city, String zip,
        String company, String image) {

    ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
    int rawContactInsertIndex = operationList.size();

    ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
    builder.withValue(RawContacts.ACCOUNT_NAME, account.name);
    builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);
    builder.withValue(RawContacts.SYNC1, partner_id);
    operationList.add(builder.build());//from  w  ww  . ja v a  2 s  .  c  o  m

    // Display Name
    builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
    builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
    builder.withValue(ContactsContract.Data.MIMETYPE,
            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
    builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name);
    operationList.add(builder.build());

    // Connection to send message from contact
    builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
    builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
    builder.withValue(ContactsContract.Data.MIMETYPE, "vnd.android.cursor.item/vnd.com.openerp.auth.profile");
    builder.withValue(ContactsContract.Data.DATA1, name);
    builder.withValue(ContactsContract.Data.DATA2, partner_id);
    builder.withValue(ContactsContract.Data.DATA3, "Send Message");
    operationList.add(builder.build());

    // Email
    if (!mail.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Email.DATA, mail);
        operationList.add(builder.build());
    }

    // Phone number
    if (!number.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number);
        operationList.add(builder.build());
    }

    // Mobile number
    if (!mobile.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, mobile);
        builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        operationList.add(builder.build());
    }

    // Website
    if (!website.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.Website.TYPE, website);
        operationList.add(builder.build());
    }

    // Address street 1
    if (!street.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, street);
        operationList.add(builder.build());
    }

    // Address street 2
    if (!street2.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, street2);
        operationList.add(builder.build());
    }

    // Address City
    if (!city.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, city);
        operationList.add(builder.build());
    }

    // Zip code
    if (!zip.equals("false")) {
        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredPostal.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, zip);
        operationList.add(builder.build());
    }

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    // Partner Image
    if (!image.equals("false")) {

        Bitmap bitmapOrg = Base64Helper.getBitmapImage(context, image);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 100, stream);

        operationList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, stream.toByteArray()).build());
    }

    // Organization
    if (!company.equals("false")) {
        operationList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
                .withValue(ContactsContract.CommonDataKinds.Organization.TYPE,
                        ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                .build());
    }

    try {
        mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.linphone.ContactEditorFragment.java

private void deleteExistingContact() {
    String select = ContactsContract.Data.CONTACT_ID + " = ?";
    String[] args = new String[] { contact.getID() };

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
            .withSelection(select, args).build());

    try {/*from  w  w  w . ja  v  a2s .c  o  m*/
        getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        ContactsManager.getInstance().removeAllFriends(contact);
    } catch (Exception e) {
        Log.w(e.getMessage() + ":" + e.getStackTrace());
    }
}

From source file:com.mobileglobe.android.customdialer.common.model.AccountTypeManager.java

/**
 * Loads account list and corresponding account types (potentially with data sets). Always
 * called on a background thread.//from  w  ww.  j a v  a 2s  .c  om
 */
protected void loadAccountsInBackground() {
    if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
        Log.d(Constants.PERFORMANCE_TAG, "AccountTypeManager.loadAccountsInBackground start");
    }
    TimingLogger timings = new TimingLogger(TAG, "loadAccountsInBackground");
    final long startTime = SystemClock.currentThreadTimeMillis();
    final long startTimeWall = SystemClock.elapsedRealtime();

    // Account types, keyed off the account type and data set concatenation.
    final Map<AccountTypeWithDataSet, AccountType> accountTypesByTypeAndDataSet = Maps.newHashMap();

    // The same AccountTypes, but keyed off {@link RawContacts#ACCOUNT_TYPE}.  Since there can
    // be multiple account types (with different data sets) for the same type of account, each
    // type string may have multiple AccountType entries.
    final Map<String, List<AccountType>> accountTypesByType = Maps.newHashMap();

    final List<AccountWithDataSet> allAccounts = Lists.newArrayList();
    final List<AccountWithDataSet> contactWritableAccounts = Lists.newArrayList();
    final List<AccountWithDataSet> groupWritableAccounts = Lists.newArrayList();
    final Set<String> extensionPackages = Sets.newHashSet();

    final AccountManager am = mAccountManager;

    final SyncAdapterType[] syncs = ContentResolver.getSyncAdapterTypes();
    final AuthenticatorDescription[] auths = am.getAuthenticatorTypes();

    // First process sync adapters to find any that provide contact data.
    for (SyncAdapterType sync : syncs) {
        if (!ContactsContract.AUTHORITY.equals(sync.authority)) {
            // Skip sync adapters that don't provide contact data.
            continue;
        }

        // Look for the formatting details provided by each sync
        // adapter, using the authenticator to find general resources.
        final String type = sync.accountType;
        final AuthenticatorDescription auth = findAuthenticator(auths, type);
        if (auth == null) {
            Log.w(TAG, "No authenticator found for type=" + type + ", ignoring it.");
            continue;
        }

        AccountType accountType;
        if (GoogleAccountType.ACCOUNT_TYPE.equals(type)) {
            accountType = new GoogleAccountType(mContext, auth.packageName);
        } else if (ExchangeAccountType.isExchangeType(type)) {
            accountType = new ExchangeAccountType(mContext, auth.packageName, type);
        } else if (SamsungAccountType.isSamsungAccountType(mContext, type, auth.packageName)) {
            accountType = new SamsungAccountType(mContext, auth.packageName, type);
        } else {
            Log.d(TAG, "Registering external account type=" + type + ", packageName=" + auth.packageName);
            accountType = new ExternalAccountType(mContext, auth.packageName, false);
        }
        if (!accountType.isInitialized()) {
            if (accountType.isEmbedded()) {
                throw new IllegalStateException(
                        "Problem initializing embedded type " + accountType.getClass().getCanonicalName());
            } else {
                // Skip external account types that couldn't be initialized.
                continue;
            }
        }

        accountType.accountType = auth.type;
        accountType.titleRes = auth.labelId;
        accountType.iconRes = auth.iconId;

        addAccountType(accountType, accountTypesByTypeAndDataSet, accountTypesByType);

        // Check to see if the account type knows of any other non-sync-adapter packages
        // that may provide other data sets of contact data.
        extensionPackages.addAll(accountType.getExtensionPackageNames());
    }

    // If any extension packages were specified, process them as well.
    if (!extensionPackages.isEmpty()) {
        Log.d(TAG, "Registering " + extensionPackages.size() + " extension packages");
        for (String extensionPackage : extensionPackages) {
            ExternalAccountType accountType = new ExternalAccountType(mContext, extensionPackage, true);
            if (!accountType.isInitialized()) {
                // Skip external account types that couldn't be initialized.
                continue;
            }
            if (!accountType.hasContactsMetadata()) {
                Log.w(TAG, "Skipping extension package " + extensionPackage + " because"
                        + " it doesn't have the CONTACTS_STRUCTURE metadata");
                continue;
            }
            if (TextUtils.isEmpty(accountType.accountType)) {
                Log.w(TAG, "Skipping extension package " + extensionPackage + " because"
                        + " the CONTACTS_STRUCTURE metadata doesn't have the accountType" + " attribute");
                continue;
            }
            Log.d(TAG, "Registering extension package account type=" + accountType.accountType + ", dataSet="
                    + accountType.dataSet + ", packageName=" + extensionPackage);

            addAccountType(accountType, accountTypesByTypeAndDataSet, accountTypesByType);
        }
    }
    timings.addSplit("Loaded account types");

    Account[] accounts = mAccountManager.getAccounts();
    for (Account account : accounts) {
        boolean syncable = ContentResolver.getIsSyncable(account, ContactsContract.AUTHORITY) > 0;

        if (syncable) {
            List<AccountType> accountTypes = accountTypesByType.get(account.type);
            if (accountTypes != null) {
                // Add an account-with-data-set entry for each account type that is
                // authenticated by this account.
                for (AccountType accountType : accountTypes) {
                    AccountWithDataSet accountWithDataSet = new AccountWithDataSet(account.name, account.type,
                            accountType.dataSet);
                    allAccounts.add(accountWithDataSet);
                    if (accountType.areContactsWritable()) {
                        contactWritableAccounts.add(accountWithDataSet);
                    }
                    if (accountType.isGroupMembershipEditable()) {
                        groupWritableAccounts.add(accountWithDataSet);
                    }
                }
            }
        }
    }

    Collections.sort(allAccounts, ACCOUNT_COMPARATOR);
    Collections.sort(contactWritableAccounts, ACCOUNT_COMPARATOR);
    Collections.sort(groupWritableAccounts, ACCOUNT_COMPARATOR);

    timings.addSplit("Loaded accounts");

    synchronized (this) {
        mAccountTypesWithDataSets = accountTypesByTypeAndDataSet;
        mAccounts = allAccounts;
        mContactWritableAccounts = contactWritableAccounts;
        mGroupWritableAccounts = groupWritableAccounts;
        mInvitableAccountTypes = findAllInvitableAccountTypes(mContext, allAccounts,
                accountTypesByTypeAndDataSet);
    }

    timings.dumpToLog();
    final long endTimeWall = SystemClock.elapsedRealtime();
    final long endTime = SystemClock.currentThreadTimeMillis();

    Log.i(TAG,
            "Loaded meta-data for " + mAccountTypesWithDataSets.size() + " account types, " + mAccounts.size()
                    + " accounts in " + (endTimeWall - startTimeWall) + "ms(wall) " + (endTime - startTime)
                    + "ms(cpu)");

    if (mInitializationLatch != null) {
        mInitializationLatch.countDown();
        mInitializationLatch = null;
    }
    if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
        Log.d(Constants.PERFORMANCE_TAG, "AccountTypeManager.loadAccountsInBackground finish");
    }

    // Check filter validity since filter may become obsolete after account update. It must be
    // done from UI thread.
    mMainThreadHandler.post(mCheckFilterValidityRunnable);
}

From source file:edu.cmu.cylab.starslinger.view.SaveActivity.java

@Override
public void onAccountsUpdated(Account[] a) {
    MyLog.i(TAG, "Account list update detected");
    // Clear out any old data to prevent duplicates
    mAccounts.clear();/*ww w . ja  v  a2  s  .c o  m*/

    // Get account data from system
    AuthenticatorDescription[] accountTypes = AccountManager.get(this).getAuthenticatorTypes();

    // Also, get a list of all sync adapters and find the ones that
    // support contacts:
    SyncAdapterType[] syncs = ContentResolver.getSyncAdapterTypes();
    ArrayList<String> contactAccountTypes = new ArrayList<String>();
    for (SyncAdapterType sync : syncs) {
        if (ContactsContract.AUTHORITY.equals(sync.authority) && sync.supportsUploading()) {
            contactAccountTypes.add(sync.accountType);
        }
    }

    // Populate tables
    for (int i = 0; i < a.length; i++) {
        // The user may have multiple accounts with the same name, so we
        // need to construct a
        // meaningful display name for each.
        String systemAccountType = a[i].type;
        AuthenticatorDescription ad = getAuthenticatorDescription(systemAccountType, accountTypes);
        if (ad != null) {
            AccountData data = new AccountData(this, a[i].name, ad);

            // filter on accounts that support contacts
            if (contactAccountTypes.contains(a[i].type))
                mAccounts.add(data);
        }
    }

    // unsync account
    AuthenticatorDescription adNull = new AuthenticatorDescription(mUnsyncType, UNSYNC_PKG, 0, 0, 0, 0);
    AccountData aNull = new AccountData(this, mUnsyncName, adNull);
    mAccounts.add(aNull);

    // Update the account spinner
    mAccountAdapter.notifyDataSetChanged();
}

From source file:com.android.contacts.ContactSaveService.java

private void createRawContact(Intent intent) {
    String accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME);
    String accountType = intent.getStringExtra(EXTRA_ACCOUNT_TYPE);
    String dataSet = intent.getStringExtra(EXTRA_DATA_SET);
    List<ContentValues> valueList = intent.getParcelableArrayListExtra(EXTRA_CONTENT_VALUES);
    Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);

    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
    operations.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
            .withValue(RawContacts.ACCOUNT_NAME, accountName).withValue(RawContacts.ACCOUNT_TYPE, accountType)
            .withValue(RawContacts.DATA_SET, dataSet).build());

    int size = valueList.size();
    for (int i = 0; i < size; i++) {
        ContentValues values = valueList.get(i);
        values.keySet().retainAll(ALLOWED_DATA_COLUMNS);
        operations.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
                .withValueBackReference(Data.RAW_CONTACT_ID, 0).withValues(values).build());
    }//from  w w w. j a va  2  s.  c o m

    ContentResolver resolver = getContentResolver();
    ContentProviderResult[] results;
    try {
        results = resolver.applyBatch(ContactsContract.AUTHORITY, operations);
    } catch (Exception e) {
        throw new RuntimeException("Failed to store new contact", e);
    }

    Uri rawContactUri = results[0].uri;
    callbackIntent.setData(RawContacts.getContactLookupUri(resolver, rawContactUri));

    deliverCallback(callbackIntent);
}

From source file:mobisocial.musubi.service.AddressBookUpdateHandler.java

@Override
public void onChange(boolean selfChange) {
    final DatabaseManager dbManager = new DatabaseManager(mContext);
    if (!dbManager.getIdentitiesManager().hasConnectedAccounts()) {
        Log.w(TAG, "no connected accounts, skipping friend import");
        return;//from www  .j a  v  a 2  s.  c  o m
    }

    //a new meta contact appears (and the previous ones disappear) if the user merges
    //or if a new entry is added, we can detect the ones that have changed by
    //this condition
    long highestContactIdAlreadySeen = dbManager.getContactDataVersionManager().getMaxContactIdSeen();
    //a new data item corresponds with a new contact, but its possible
    //that a users just adds a new contact method to an existing contact
    //and we need to detect that
    long highestDataIdAlreadySeen = dbManager.getContactDataVersionManager().getMaxDataIdSeen();

    // BJD -- this didn't end up being faster once all import features were added.
    /*if (highestContactIdAlreadySeen == -1) {
       importFullAddressBook(mContext);
       return;
    }*/
    long now = System.currentTimeMillis();
    if (mLastRun + ONCE_PER_PERIOD > now) {
        //wake up when the period expires
        if (!mScheduled) {
            new Handler(mThread.getLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScheduled = false;
                    dispatchChange(false);
                }
            }, ONCE_PER_PERIOD - (now - mLastRun) + 1);
        }
        mScheduled = true;
        //skip this update
        return;
    }
    Log.i(TAG, "waking up to handle contact changes...");
    boolean identityAdded = false, profileDataChanged = false;
    Date start = new Date();

    assert (SYNC_EMAIL);
    String account_type_selection = getAccountSelectionString();

    Cursor c = mContext.getContentResolver().query(
            ContactsContract.Data.CONTENT_URI, new String[] { ContactsContract.Data._ID,
                    ContactsContract.Data.DATA_VERSION, ContactsContract.Data.CONTACT_ID },
            "(" + ContactsContract.Data.DATA_VERSION + ">0 OR " + //maybe updated
                    ContactsContract.Data.CONTACT_ID + ">? OR " + //definitely new or merged
                    ContactsContract.Data._ID + ">? " + //definitely added a data item
                    ") AND (" + ContactsContract.RawContacts.ACCOUNT_TYPE + "<>'" + mAccountType + "'"
                    + ") AND (" + NAME_OR_OTHER_SELECTION + account_type_selection + ")", // All known contacts.
            new String[] { String.valueOf(highestContactIdAlreadySeen),
                    String.valueOf(highestDataIdAlreadySeen) },
            null);

    if (c == null) {
        Log.e(TAG, "no valid cursor", new Throwable());
        mContext.getContentResolver().notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, this);
        return;
    }

    HashMap<Pair<String, String>, MMyAccount> account_mapping = new HashMap<Pair<String, String>, MMyAccount>();
    int max_changes = c.getCount();
    TLongArrayList raw_data_ids = new TLongArrayList(max_changes);
    TLongArrayList versions = new TLongArrayList(max_changes);
    long new_max_data_id = highestDataIdAlreadySeen;
    long new_max_contact_id = highestContactIdAlreadySeen;
    TLongHashSet potentially_changed = new TLongHashSet();
    try {
        //the cursor points to a list of raw contact data items that may have changed
        //the items will include a type specific field that we are interested in updating
        //it is possible that multiple data item entries mention the same identifier
        //so we build a list of contacts to update and then perform synchronization
        //by refreshing given that we know the top level contact id.
        if (DBG)
            Log.d(TAG, "Scanning " + c.getCount() + " contacts...");
        while (c.moveToNext()) {
            if (DBG)
                Log.v(TAG, "check for updates of contact " + c.getLong(0));

            long raw_data_id = c.getLong(0);
            long version = c.getLong(1);
            long contact_id = c.getLong(2);

            //if the contact was split or merged, then we get a higher contact id
            //so if we have a higher id, data version doesnt really matter
            if (contact_id <= highestContactIdAlreadySeen) {
                //the data associated with this contact may not be dirty
                //we just can't do the join against our table because thise
                //api is implmented over the content provider
                if (dbManager.getContactDataVersionManager().getVersion(raw_data_id) == version)
                    continue;
            } else {
                new_max_contact_id = Math.max(new_max_contact_id, contact_id);
            }
            raw_data_ids.add(raw_data_id);
            versions.add(version);
            potentially_changed.add(contact_id);
            new_max_data_id = Math.max(new_max_data_id, raw_data_id);
        }
        if (DBG)
            Log.d(TAG, "Finished iterating over " + c.getCount() + " contacts for " + potentially_changed.size()
                    + " candidates.");
    } finally {
        c.close();
    }
    if (potentially_changed.size() == 0) {
        Log.w(TAG,
                "possible bug, woke up to update contacts, but no change was detected; there are extra wakes so it could be ok");
    }

    final SQLiteDatabase db = dbManager.getDatabase();

    Pattern emailPattern = getEmailPattern();
    Pattern numberPattern = getNumberPattern();
    //slice it up so we don't use too much system resource on keeping a lot of state in memory
    int total = potentially_changed.size();
    sAddressBookTotal = total;
    sAddressBookPosition = 0;

    final TLongArrayList slice_of_changed = new TLongArrayList(BATCH_SIZE);
    final StringBuilder to_fetch = new StringBuilder();
    final HashMap<Pair<String, String>, TLongHashSet> ids_for_account = new HashMap<Pair<String, String>, TLongHashSet>();
    final TLongObjectHashMap<String> names = new TLongObjectHashMap<String>();

    TLongIterator it = potentially_changed.iterator();
    for (int i = 0; i < total && it.hasNext();) {
        sAddressBookPosition = i;

        if (BootstrapActivity.isBootstrapped()) {
            try {
                Thread.sleep(mSleepTime * SLEEP_SCALE);
            } catch (InterruptedException e) {
            }
        }

        slice_of_changed.clear();
        ids_for_account.clear();
        names.clear();

        int max = i + BATCH_SIZE;
        for (; i < max && it.hasNext(); ++i) {
            slice_of_changed.add(it.next());
        }

        if (DBG)
            Log.v(TAG, "looking up names ");
        to_fetch.setLength(0);
        to_fetch.append(ContactsContract.Contacts._ID + " IN ");
        SQLClauseHelper.appendArray(to_fetch, slice_of_changed.iterator());
        //lookup the fields we care about from a user profile perspective
        c = mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, },
                to_fetch.toString(), null, null);
        try {
            while (c.moveToNext()) {
                long id = c.getLong(0);
                String name = c.getString(1);
                if (name == null)
                    continue;
                //reject names that are just the email address or are just a number 
                //the default for android is just to propagate this as the name
                //if there is no name
                if (emailPattern.matcher(name).matches() || numberPattern.matcher(name).matches())
                    continue;
                names.put(id, name);
            }
        } finally {
            c.close();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            db.beginTransactionNonExclusive();
        } else {
            db.beginTransaction();
        }

        long before = SystemClock.elapsedRealtime();
        SliceUpdater updater = new SliceUpdater(dbManager, slice_of_changed, ids_for_account, names,
                account_type_selection);
        long after = SystemClock.elapsedRealtime();
        mSleepTime = (mSleepTime + after - before) / 2;
        slice_of_changed.forEach(updater);
        profileDataChanged |= updater.profileDataChanged;
        identityAdded |= updater.identityAdded;
        db.setTransactionSuccessful();
        db.endTransaction();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            db.beginTransactionNonExclusive();
        } else {
            db.beginTransaction();
        }
        //add all detected members to account feed
        for (Entry<Pair<String, String>, TLongHashSet> e : ids_for_account.entrySet()) {
            Pair<String, String> k = e.getKey();
            TLongHashSet v = e.getValue();
            MMyAccount cached_account = account_mapping.get(k);
            if (cached_account == null) {
                cached_account = lookupOrCreateAccount(dbManager, k.getValue0(), k.getValue1());
                prepareAccountWhitelistFeed(dbManager.getMyAccountManager(), dbManager.getFeedManager(),
                        cached_account);
                account_mapping.put(k, cached_account);
            }

            final MMyAccount account = cached_account;
            v.forEach(new TLongProcedure() {
                @Override
                public boolean execute(long id) {
                    dbManager.getFeedManager().ensureFeedMember(account.feedId_, id);
                    db.yieldIfContendedSafely(75);
                    return true;
                }
            });
        }
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    sAddressBookTotal = sAddressBookPosition = 0;

    //TODO: handle deleted
    //for all android data ids in our table, check if they still exist in the
    //contacts table, probably in batches of 100 or something.  if they don't
    //null them out.  this is annoyingly non-differential.

    //TODO: adding friend should update accepted feed status, however,
    //if a crashe happens for whatever reason, then its possible that this may need to
    //be run for identities which actually exist in the db.  so this update code
    //needs to do the feed accepted status change for all users that were touched
    //by the profile update process

    //update the version ids so we can be faster on subsequent runs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        db.beginTransactionNonExclusive();
    } else {
        db.beginTransaction();
    }
    int changed_data_rows = raw_data_ids.size();
    for (int i = 0; i < changed_data_rows; ++i) {
        dbManager.getContactDataVersionManager().setVersion(raw_data_ids.get(i), versions.get(i));
    }
    db.setTransactionSuccessful();
    db.endTransaction();

    dbManager.getContactDataVersionManager().setMaxDataIdSeen(new_max_data_id);
    dbManager.getContactDataVersionManager().setMaxContactIdSeen(new_max_contact_id);
    ContentResolver resolver = mContext.getContentResolver();

    Date end = new Date();
    double time = end.getTime() - start.getTime();
    time /= 1000;
    Log.w(TAG, "update address book " + mChangeCount++ + " took " + time + " seconds");
    if (identityAdded) {
        //wake up the profile push
        resolver.notifyChange(MusubiService.WHITELIST_APPENDED, this);
    }
    if (profileDataChanged) {
        //refresh the ui...
        resolver.notifyChange(MusubiService.PRIMARY_CONTENT_CHANGED, this);
    }
    if (identityAdded || profileDataChanged) {
        //update the our musubi address book as needed.
        String accountName = mContext.getString(R.string.account_name);
        String accountType = mContext.getString(R.string.account_type);
        Account account = new Account(accountName, accountType);
        ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle());
    }

    dbManager.close();
    mLastRun = new Date().getTime();
    resolver.notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, this);
}

From source file:org.sufficientlysecure.keychain.util.ContactHelper.java

private void writeKeysToNormalContacts() {
    // delete raw contacts flagged for deletion by user so they can be reinserted
    deleteFlaggedNormalRawContacts();/*from w  w w .  j a va2 s . c  om*/

    Set<Long> deletedKeys = getRawContactMasterKeyIds();

    // Load all public Keys from OK
    // TODO: figure out why using selectionArgs does not work in this case
    Cursor cursor = mContentResolver.query(KeychainContract.KeyRings.buildUnifiedKeyRingsUri(),
            KEYS_TO_CONTACT_PROJECTION, KeychainContract.KeyRings.HAS_ANY_SECRET + "=0", null, null);

    if (cursor != null) {
        while (cursor.moveToNext()) {
            long masterKeyId = cursor.getLong(INDEX_MASTER_KEY_ID);
            OpenPgpUtils.UserId userIdSplit = KeyRing.splitUserId(cursor.getString(INDEX_USER_ID));
            boolean isExpired = cursor.getInt(INDEX_IS_EXPIRED) != 0;
            boolean isRevoked = cursor.getInt(INDEX_IS_REVOKED) > 0;
            boolean isVerified = cursor.getInt(INDEX_VERIFIED) > 0;

            Log.d(Constants.TAG, "masterKeyId: " + masterKeyId);

            deletedKeys.remove(masterKeyId);

            ArrayList<ContentProviderOperation> ops = new ArrayList<>();

            // Do not store expired or revoked or unverified keys in contact db - and
            // remove them if they already exist. Secret keys do not reach this point
            if (isExpired || isRevoked || !isVerified) {
                Log.d(Constants.TAG, "Expired or revoked or unverified: Deleting masterKeyId " + masterKeyId);
                if (masterKeyId != -1) {
                    deleteRawContactByMasterKeyId(masterKeyId);
                }
            } else if (userIdSplit.name != null) {

                // get raw contact to this master key id
                long rawContactId = findRawContactId(masterKeyId);
                Log.d(Constants.TAG, "rawContactId: " + rawContactId);

                // Create a new rawcontact with corresponding key if it does not exist yet
                if (rawContactId == -1) {
                    Log.d(Constants.TAG, "Insert new raw contact with masterKeyId " + masterKeyId);

                    insertContact(ops, masterKeyId);
                    writeContactKey(ops, rawContactId, masterKeyId, userIdSplit.name);
                }

                // We always update the display name (which is derived from primary user id)
                // and email addresses from user id
                writeContactDisplayName(ops, rawContactId, userIdSplit.name);
                writeContactEmail(ops, rawContactId, masterKeyId);
                try {
                    mContentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
                } catch (Exception e) {
                    Log.w(Constants.TAG, e);
                }
            }
        }
        cursor.close();
    }

    // Delete master key ids that are no longer present in OK
    for (Long masterKeyId : deletedKeys) {
        Log.d(Constants.TAG, "Delete raw contact with masterKeyId " + masterKeyId);
        deleteRawContactByMasterKeyId(masterKeyId);
    }
}

From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

private void deleteUnsyncedItems(ContentProviderClient provider, Account account, SyncResult syncResult)
        throws RemoteException, JSONException {

    Log.d(TAG, "Delete unsynced items before count: " + syncResult.stats.numDeletes);
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ContentProviderOperation op;//from   ww w. ja v a 2 s .  co  m
    ContentProviderResult[] results;

    // This is the good part
    Cursor unsyncedGroupsCursor = null;
    try {
        final String SELECT = GMSGroup.STATUS + " ISNULL OR " + GMSGroup.STATUS + " != "
                + GMSGroup.STATUS_SYNCED;
        unsyncedGroupsCursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup._ID,
                GMSGroup.CLOUD_ID, GMSGroup.STATUS, GMSGroup.NAME, GMSGroup.RAW_CONTACT_ID }, SELECT, null,
                null);
        ContentProviderClient contactsProvider;
        if (unsyncedGroupsCursor.moveToFirst()) {
            contactsProvider = getContext().getContentResolver()
                    .acquireContentProviderClient(ContactsContract.AUTHORITY);
            do {
                long groupId = unsyncedGroupsCursor.getLong(0);
                long groupRawContactId = unsyncedGroupsCursor.getLong(4);
                Cursor memberCursor = null;
                try {
                    memberCursor = provider.query(GMSContacts.CONTENT_URI,
                            new String[] { GMSContact._ID, GMSContact.GROUP_ID }, GMSContact.GROUP_ID + "=?",
                            new String[] { String.valueOf(groupId) }, null);
                    while (memberCursor.moveToNext()) {
                        op = ContentProviderOperation.newDelete(
                                ContentUris.withAppendedId(GMSContacts.CONTENT_URI, memberCursor.getLong(0)))
                                .build();
                        ops.add(op);
                    }
                } finally {
                    if (memberCursor != null) {
                        memberCursor.close();
                    }
                }
                op = ContentProviderOperation
                        .newDelete(ContentUris.withAppendedId(GMSGroups.CONTENT_URI, groupId)).build();
                ops.add(op);
                if (groupRawContactId <= 0) {
                    Cursor accountContactsCursor = null;
                    try {
                        String sourceId = unsyncedGroupsCursor.getString(1);
                        Log.d(TAG, String.format("Unsynced Group Id: %1$d, SourceId: %2$s", groupId, sourceId));
                        accountContactsCursor = GMSContactOperations.findGroupInContacts(contactsProvider,
                                account, sourceId);
                        if (accountContactsCursor != null && accountContactsCursor.moveToFirst()) {
                            groupRawContactId = accountContactsCursor.getLong(0);
                        }
                    } finally {
                        if (accountContactsCursor != null) {
                            accountContactsCursor.close();
                        }
                    }
                    GMSContactOperations.removeGroupFromContacts(contactsProvider, account, groupRawContactId,
                            syncResult);
                }
            } while (unsyncedGroupsCursor.moveToNext());
        }
    } finally {
        if (unsyncedGroupsCursor != null) {
            unsyncedGroupsCursor.close();
        }
    }
    // Now delete any unsynced contacts from the local provider
    op = ContentProviderOperation.newDelete(GMSContacts.CONTENT_URI)
            .withSelection(
                    GMSContact.STATUS + " ISNULL OR " + GMSContact.STATUS + " != " + GMSContact.STATUS_SYNCED,
                    null)
            .build();
    ops.add(op);

    op = ContentProviderOperation.newUpdate(GMSGroups.CONTENT_URI).withValue(GMSGroup.STATUS, null).build();
    ops.add(op);

    op = ContentProviderOperation.newUpdate(GMSContacts.CONTENT_URI).withValue(GMSContact.STATUS, null).build();
    ops.add(op);
    try {
        results = provider.applyBatch(ops);
        int numResults = results.length;
        for (int i = 0; i < numResults; ++i) {
            // The first first N-2 results were deletes
            if (i < numResults - 2) {
                syncResult.stats.numDeletes += results[i].count;
            } else {
                // The last two results were updates
                syncResult.stats.numEntries += results[i].count;
            }
        }
        Log.d(TAG, String.format("Delete unsynced items after count: %1$d, entries: %2$d",
                syncResult.stats.numDeletes, syncResult.stats.numEntries));
    } catch (OperationApplicationException e) {
        syncResult.stats.numSkippedEntries++;
        e.printStackTrace();
    }
}

From source file:org.sufficientlysecure.keychain.util.ContactHelper.java

/**
 * Links all keys with secrets to the main ("me") contact
 * http://developer.android.com/reference/android/provider/ContactsContract.Profile.html
 */// w  w w. j  av  a  2 s.co m
private void writeKeysToMainProfileContact() {
    // deletes contacts hidden by the user so they can be reinserted if necessary
    deleteFlaggedMainProfileRawContacts();

    Set<Long> keysToDelete = getMainProfileMasterKeyIds();

    // get all keys which have associated secret keys
    // TODO: figure out why using selectionArgs does not work in this case
    Cursor cursor = mContentResolver.query(KeychainContract.KeyRings.buildUnifiedKeyRingsUri(),
            KEYS_TO_CONTACT_PROJECTION, KeychainContract.KeyRings.HAS_ANY_SECRET + "!=0", null, null);
    if (cursor != null)
        try {
            while (cursor.moveToNext()) {
                long masterKeyId = cursor.getLong(INDEX_MASTER_KEY_ID);
                boolean isExpired = cursor.getInt(INDEX_IS_EXPIRED) != 0;
                boolean isRevoked = cursor.getInt(INDEX_IS_REVOKED) > 0;
                OpenPgpUtils.UserId userIdSplit = KeyRing.splitUserId(cursor.getString(INDEX_USER_ID));

                if (!isExpired && !isRevoked && userIdSplit.name != null) {
                    // if expired or revoked will not be removed from keysToDelete or inserted
                    // into main profile ("me" contact)
                    boolean existsInMainProfile = keysToDelete.remove(masterKeyId);
                    if (!existsInMainProfile) {
                        long rawContactId = -1;//new raw contact

                        Log.d(Constants.TAG, "masterKeyId with secret " + masterKeyId);

                        ArrayList<ContentProviderOperation> ops = new ArrayList<>();
                        insertMainProfileRawContact(ops, masterKeyId);
                        writeContactKey(ops, rawContactId, masterKeyId, userIdSplit.name);

                        try {
                            mContentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
                        } catch (Exception e) {
                            Log.w(Constants.TAG, e);
                        }
                    }
                }
            }
        } finally {
            cursor.close();
        }

    for (long masterKeyId : keysToDelete) {
        deleteMainProfileRawContactByMasterKeyId(masterKeyId);
        Log.d(Constants.TAG, "Delete main profile raw contact with masterKeyId " + masterKeyId);
    }
}

From source file:com.forktech.cmerge.ui.ContactsListFragment.java

private void mergeContacts() {
    ArrayList<Integer> list = (ArrayList<Integer>) getContacts();
    int numOfContacts = list.size();

    if (numOfContacts < 2) {
        Toast.makeText(getActivity(), "Atleast select two contacts to merge", Toast.LENGTH_SHORT).show();
        return;/*  w ww . j a v  a2  s . c om*/
    }
    mAdapter.clearChecks(true);
    for (int i = 0; i < numOfContacts - 1; i++) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        ops.add(ContentProviderOperation.newUpdate(ContactsContract.AggregationExceptions.CONTENT_URI)
                .withValue(ContactsContract.AggregationExceptions.TYPE,
                        ContactsContract.AggregationExceptions.TYPE_KEEP_TOGETHER)
                .withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, getContacts().get(0))
                .withValue(ContactsContract.AggregationExceptions.RAW_CONTACT_ID2, getContacts().get(i + 1))
                .build());
        // Log.e("", Arrays.deepToString(getContacts().toArray()));

        try {
            ContentProviderResult[] result = getActivity().getContentResolver()
                    .applyBatch(ContactsContract.AUTHORITY, ops);
            Log.e("",
                    "result length : " + result.length + " :: " + result[0].uri + result[0].describeContents());
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        }
    }
}