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:pt.up.mobile.syncadapter.SigarraSyncAdapter.java

private void syncProfiles(Account account, SyncResult syncResult)
        throws AuthenticationException, IOException, JSONException {
    final User user = AccountUtils.getUser(getContext(), account.name);
    final String profile;
    if (user.getType().equals(SifeupAPI.STUDENT_TYPE)) {
        profile = SifeupAPI.getReply(SifeupAPI.getStudenProfiletUrl(user.getUserCode()), account, getContext());
    } else {/*w w w. j a v a  2s  .  com*/
        profile = SifeupAPI.getReply(SifeupAPI.getEmployeeProfileUrl(user.getUserCode()), account,
                getContext());
    }
    final String picPath = getProfilePic(user.getUserCode(), account, syncResult);
    final ContentValues values = new ContentValues();
    values.put(SigarraContract.ProfileColumns.ID, user.getUserCode());
    values.put(SigarraContract.ProfileColumns.CONTENT, profile);
    if (picPath != null)
        values.put(SigarraContract.ProfileColumns.PIC, picPath);
    values.put(BaseColumns.COLUMN_STATE, SyncStates.KEEP);
    getContext().getContentResolver().insert(SigarraContract.Profiles.CONTENT_URI, values);
    syncResult.stats.numEntries += 1;
    final Cursor c = getContext().getContentResolver().query(SigarraContract.Friends.CONTENT_URI,
            new String[] { SigarraContract.FriendsColumns.CODE_FRIEND,
                    SigarraContract.FriendsColumns.TYPE_FRIEND },
            SigarraContract.Friends.USER_FRIENDS,
            SigarraContract.Friends.getUserFriendsSelectionArgs(user.getUserCode()), null);
    try {
        if (c.moveToFirst()) {
            final ContentValues[] friends = new ContentValues[c.getCount()];
            int i = 0;
            do {
                final ContentValues friendValues = new ContentValues();
                final String friendCode = c
                        .getString(c.getColumnIndex(SigarraContract.FriendsColumns.CODE_FRIEND));
                final String friendPic = getProfilePic(friendCode, account, syncResult);
                friendValues.put(SigarraContract.ProfileColumns.ID, friendCode);
                final String friendType = c
                        .getString(c.getColumnIndex(SigarraContract.FriendsColumns.TYPE_FRIEND));
                final String friendPage;
                if (friendType.equals(SifeupAPI.STUDENT_TYPE)) {
                    friendPage = SifeupAPI.getReply(SifeupAPI.getStudenProfiletUrl(friendCode), account,
                            getContext());
                } else {
                    friendPage = SifeupAPI.getReply(SifeupAPI.getEmployeeProfileUrl(friendCode), account,
                            getContext());
                }
                friendValues.put(SigarraContract.ProfileColumns.CONTENT, friendPage);
                if (friendPic != null)
                    friendValues.put(SigarraContract.ProfileColumns.PIC, friendPic);
                friendValues.put(BaseColumns.COLUMN_STATE, SyncStates.KEEP);
                friends[i++] = friendValues;
            } while (c.moveToNext());
            getContext().getContentResolver().bulkInsert(SigarraContract.Profiles.CONTENT_URI, friends);
            syncResult.stats.numEntries += friends.length;
        }
    } finally {
        c.close();
    }
    // Request sync for the contacts, if it is disabled in Settings
    // the sync won't be called
    ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle());
}

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

/**
 * Splits "diff" into subsets based on "MAX_CONTACTS_PROVIDER_BATCH_SIZE", applies each of the
 * subsets, adds the returned array to "results".
 *
 * @return the size of the array, if not null; -1 when the array is null.
 */// w ww.j ava 2  s.c  om
private int applyDiffSubset(ArrayList<ContentProviderOperation> diff, int offset,
        ContentProviderResult[] results, ContentResolver resolver)
        throws RemoteException, OperationApplicationException {
    final int subsetCount = Math.min(diff.size() - offset, MAX_CONTACTS_PROVIDER_BATCH_SIZE);
    final ArrayList<ContentProviderOperation> subset = new ArrayList<>();
    subset.addAll(diff.subList(offset, offset + subsetCount));
    final ContentProviderResult[] subsetResult = resolver.applyBatch(ContactsContract.AUTHORITY, subset);
    if (subsetResult == null || (offset + subsetResult.length) > results.length) {
        return -1;
    }
    for (ContentProviderResult c : subsetResult) {
        results[offset++] = c;
    }
    return subsetResult.length;
}

From source file:net.ddns.mlsoftlaberge.contactslist.ui.ContactAdminFragment.java

private void updatenote() {
    normalizememo();/*from  w w w.  java2s .c  o m*/
    newnote = notememo.toString() + notereformat.toString();
    // update the record
    try {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
                .withSelection(Data.RAW_CONTACT_ID + " = ?", new String[] { mNotesRawId })
                .withSelection(Data._ID + " = ?", new String[] { mNotesId })
                .withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                .withValue(Data.DATA1, newnote).build());
        getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        // inform of success
        Toast.makeText(getActivity(), "Transaction Updated", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getActivity(), "Transaction Not Updated", Toast.LENGTH_SHORT).show();
        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

From source file:net.ddns.mlsoftlaberge.contactslist.ui.ContactAdminFragment.java

public void insertnote() {
    normalizememo();/*  w ww .j  a  v a2 s .c om*/
    newnote = notememo.toString() + notereformat.toString();
    try {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI).withValue(Data.RAW_CONTACT_ID, mNotesRawId)
                .withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                .withValue(Data.DATA1, newnote).build());
        getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        Toast.makeText(getActivity(), "Transaction Inserted", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getActivity(), "Transaction Not Inserted", Toast.LENGTH_SHORT).show();
        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

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

private void addMembersToGroup(ContentResolver resolver, long[] rawContactsToAdd, long groupId) {
    if (rawContactsToAdd == null) {
        return;//from  w w  w.  ja va  2s.  c o  m
    }
    for (long rawContactId : rawContactsToAdd) {
        try {
            final ArrayList<ContentProviderOperation> rawContactOperations = new ArrayList<ContentProviderOperation>();

            // Build an assert operation to ensure the contact is not already in the group
            final ContentProviderOperation.Builder assertBuilder = ContentProviderOperation
                    .newAssertQuery(Data.CONTENT_URI);
            assertBuilder.withSelection(
                    Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID
                            + "=?",
                    new String[] { String.valueOf(rawContactId), GroupMembership.CONTENT_ITEM_TYPE,
                            String.valueOf(groupId) });
            assertBuilder.withExpectedCount(0);
            rawContactOperations.add(assertBuilder.build());

            // Build an insert operation to add the contact to the group
            final ContentProviderOperation.Builder insertBuilder = ContentProviderOperation
                    .newInsert(Data.CONTENT_URI);
            insertBuilder.withValue(Data.RAW_CONTACT_ID, rawContactId);
            insertBuilder.withValue(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
            insertBuilder.withValue(GroupMembership.GROUP_ROW_ID, groupId);
            rawContactOperations.add(insertBuilder.build());

            if (DEBUG) {
                for (ContentProviderOperation operation : rawContactOperations) {
                    Log.v(TAG, operation.toString());
                }
            }

            // Apply batch
            if (!rawContactOperations.isEmpty()) {
                resolver.applyBatch(ContactsContract.AUTHORITY, rawContactOperations);
            }
        } catch (RemoteException e) {
            // Something went wrong, bail without success
            FeedbackHelper.sendFeedback(this, TAG,
                    "Problem persisting user edits for raw contact ID " + String.valueOf(rawContactId), e);
        } catch (OperationApplicationException e) {
            // The assert could have failed because the contact is already in the group,
            // just continue to the next contact
            FeedbackHelper.sendFeedback(this, TAG, "Assert failed in adding raw contact ID "
                    + String.valueOf(rawContactId) + ". Already exists in group " + String.valueOf(groupId), e);
        }
    }
}

From source file:org.linphone.ContactsManager.java

public void removeLinphoneContactTag(Contact contact) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    String select = ContactsContract.RawContacts._ID + " = ?";
    String[] args = new String[] { findRawLinphoneContactID(contact.getID()) };

    ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
            .withSelection(select, args).build());

    try {/* w w w.ja v a  2s.  c  om*/
        contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        Log.w(e.getMessage() + ":" + e.getStackTrace());
    }
}

From source file:com.android.contacts.activities.PeopleActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mDisableOptionItemSelected) {
        return false;
    }//from  w  ww . jav  a2  s .co m

    switch (item.getItemId()) {
    case android.R.id.home: {
        // The home icon on the action bar is pressed
        if (mActionBarAdapter.isUpShowing()) {
            // "UP" icon press -- should be treated as "back".
            onBackPressed();
        }
        return true;
    }
    case R.id.menu_settings: {
        startActivity(new Intent(this, ContactsPreferenceActivity.class));
        return true;
    }
    case R.id.menu_contacts_filter: {
        AccountFilterUtil.startAccountFilterActivityForResult(this, SUBACTIVITY_ACCOUNT_FILTER,
                mContactListFilterController.getFilter());
        return true;
    }
    case R.id.menu_search: {
        onSearchRequested();
        return true;
    }
    case R.id.menu_share:
        shareSelectedContacts();
        return true;
    case R.id.menu_join:
        joinSelectedContacts();
        return true;
    case R.id.menu_delete:
        deleteSelectedContacts();
        return true;
    case R.id.menu_import_export: {
        showImportExportDialogFragment();
        return true;
    }
    case R.id.menu_clear_frequents: {
        ClearFrequentsDialog.show(getFragmentManager());
        return true;
    }
    case R.id.menu_help:
        HelpUtils.launchHelpAndFeedbackForMainScreen(this);
        return true;
    case R.id.menu_accounts: {
        final Intent intent = new Intent(Settings.ACTION_SYNC_SETTINGS);
        intent.putExtra(Settings.EXTRA_AUTHORITIES, new String[] { ContactsContract.AUTHORITY });
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        ImplicitIntentsUtil.startActivityInAppIfPossible(this, intent);
        return true;
    }
    case R.id.menu_blocked_numbers: {
        final Intent intent = TelecomManagerUtil
                .createManageBlockedNumbersIntent((TelecomManager) getSystemService(Context.TELECOM_SERVICE));
        if (intent != null) {
            startActivity(intent);
        }
        return true;
    }
    case R.id.export_database: {
        final Intent intent = new Intent("com.android.providers.contacts.DUMP_DATABASE");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        ImplicitIntentsUtil.startActivityOutsideApp(this, intent);
        return true;
    }
    }
    return false;
}

From source file:org.linphone.ContactsManager.java

public void migrateContacts() {
    Cursor oldContacts = Compatibility.getImContactsCursor(contentResolver);
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    if (oldContacts != null) {
        for (int i = 0; i < oldContacts.getCount(); i++) {
            Contact contact = Compatibility.getContact(contentResolver, oldContacts, i);
            for (String address : Compatibility.extractContactImAddresses(contact.getID(), contentResolver)) {
                if (LinphoneUtils.isSipAddress(address)) {
                    if (address.startsWith("sip:")) {
                        address = address.substring(4);
                    }/*w w w.  j a  v  a  2s. co  m*/

                    //Add new sip address
                    Compatibility.addSipAddressToContact(context, ops, address,
                            findRawContactID(contentResolver, contact.getID()));
                    try {
                        contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    ops.clear();

                    contact.refresh(contentResolver);

                    //If address sip is correctly add, remove the im address
                    if (contact.getNumbersOrAddresses().contains(address)) {
                        Compatibility.deleteImAddressFromContact(ops, address, contact.getID());
                        try {
                            contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        ops.clear();
                    } else {
                        //Add linphone friend instead
                        if (createNewFriend(contact, address)) {
                            contact.refresh(contentResolver);

                            //Remove IM address
                            Compatibility.deleteImAddressFromContact(ops, address, contact.getID());
                            try {
                                contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
                            } catch (Exception e) {
                                e.printStackTrace();

                            }
                        }
                    }
                }
                ops.clear();
            }
        }
        oldContacts.close();
    }

}

From source file:com.phonegap.ContactAccessorSdk5.java

/**
 * Creates a new contact and stores it in the database
 * //from  w w  w  .  ja  v  a 2s .  c  o  m
 * @param id the raw contact id which is required for linking items to the contact
 * @param contact the contact to be saved
 * @param account the account to be saved under
 */
private boolean modifyContact(String id, JSONObject contact, Account account) {
    // Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
    // But not needed to update existing values.
    int rawId = (new Integer(getJsonString(contact, "rawId"))).intValue();

    // Create a list of attributes to add to the contact database
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    //Add contact type
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, account.type)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, account.name).build());

    // Modify name
    JSONObject name;
    try {
        String displayName = getJsonString(contact, "displayName");
        name = contact.getJSONObject("name");
        if (displayName != null || name != null) {
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                    + "=?",
                            new String[] { id,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });

            if (displayName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
            }

            String familyName = getJsonString(name, "familyName");
            if (familyName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
            }
            String middleName = getJsonString(name, "middleName");
            if (middleName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
            }
            String givenName = getJsonString(name, "givenName");
            if (givenName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
            }
            String honorificPrefix = getJsonString(name, "honorificPrefix");
            if (honorificPrefix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
            }
            String honorificSuffix = getJsonString(name, "honorificSuffix");
            if (honorificSuffix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
            }

            ops.add(builder.build());
        }
    } catch (JSONException e1) {
        Log.d(LOG_TAG, "Could not get name");
    }

    // Modify phone numbers
    JSONArray phones = null;
    try {
        phones = contact.getJSONArray("phoneNumbers");
        if (phones != null) {
            for (int i = 0; i < phones.length(); i++) {
                JSONObject phone = (JSONObject) phones.get(i);
                String phoneId = getJsonString(phone, "id");
                // This is a new phone so do a DB insert
                if (phoneId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                            getJsonString(phone, "value"));
                    contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                            getPhoneType(getJsonString(phone, "type")));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing phone so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.CommonDataKinds.Phone._ID + "=? AND "
                                    + ContactsContract.Data.MIMETYPE + "=?",
                            new String[] { phoneId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                    getJsonString(phone, "value"))
                            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                                    getPhoneType(getJsonString(phone, "type")))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get phone numbers");
    }

    // Modify emails
    JSONArray emails = null;
    try {
        emails = contact.getJSONArray("emails");
        if (emails != null) {
            for (int i = 0; i < emails.length(); i++) {
                JSONObject email = (JSONObject) emails.get(i);
                String emailId = getJsonString(email, "id");
                // This is a new email so do a DB insert
                if (emailId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.Email.DATA,
                            getJsonString(email, "value"));
                    contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE,
                            getContactType(getJsonString(email, "type")));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing email so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.CommonDataKinds.Email._ID + "=? AND "
                                    + ContactsContract.Data.MIMETYPE + "=?",
                            new String[] { emailId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.Email.DATA,
                                    getJsonString(email, "value"))
                            .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                                    getContactType(getJsonString(email, "type")))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify addresses
    JSONArray addresses = null;
    try {
        addresses = contact.getJSONArray("addresses");
        if (addresses != null) {
            for (int i = 0; i < addresses.length(); i++) {
                JSONObject address = (JSONObject) addresses.get(i);
                String addressId = getJsonString(address, "id");
                // This is a new address so do a DB insert
                if (addressId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                            getJsonString(address, "formatted"));
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                            getJsonString(address, "streetAddress"));
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                            getJsonString(address, "locality"));
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                            getJsonString(address, "region"));
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                            getJsonString(address, "postalCode"));
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                            getJsonString(address, "country"));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing address so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND "
                                    + ContactsContract.Data.MIMETYPE + "=?",
                            new String[] { addressId,
                                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                                    getJsonString(address, "formatted"))
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                                    getJsonString(address, "streetAddress"))
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                                    getJsonString(address, "locality"))
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                                    getJsonString(address, "region"))
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                                    getJsonString(address, "postalCode"))
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                                    getJsonString(address, "country"))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get addresses");
    }

    // Modify organizations
    JSONArray organizations = null;
    try {
        organizations = contact.getJSONArray("organizations");
        if (organizations != null) {
            for (int i = 0; i < organizations.length(); i++) {
                JSONObject org = (JSONObject) organizations.get(i);
                String orgId = getJsonString(org, "id");
                ;
                // This is a new organization so do a DB insert
                if (orgId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                            getJsonString(org, "department"));
                    contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY,
                            getJsonString(org, "name"));
                    contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE,
                            getJsonString(org, "title"));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing organization so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(
                                    ContactsContract.CommonDataKinds.Organization._ID + "=? AND "
                                            + ContactsContract.Data.MIMETYPE + "=?",
                                    new String[] { orgId,
                                            ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                                    getJsonString(org, "department"))
                            .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY,
                                    getJsonString(org, "name"))
                            .withValue(ContactsContract.CommonDataKinds.Organization.TITLE,
                                    getJsonString(org, "title"))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get organizations");
    }

    // Modify IMs
    JSONArray ims = null;
    try {
        ims = contact.getJSONArray("ims");
        if (ims != null) {
            for (int i = 0; i < ims.length(); i++) {
                JSONObject im = (JSONObject) ims.get(i);
                String imId = getJsonString(im, "id");
                ;
                // This is a new IM so do a DB insert
                if (imId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
                    contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE,
                            getContactType(getJsonString(im, "type")));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing IM so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.CommonDataKinds.Im._ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                    + "=?",
                            new String[] { imId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
                            .withValue(ContactsContract.CommonDataKinds.Im.TYPE,
                                    getContactType(getJsonString(im, "type")))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify note
    String note = getJsonString(contact, "note");
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
            .withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                    new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE })
            .withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());

    // Modify nickname
    String nickname = getJsonString(contact, "nickname");
    if (nickname != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE })
                .withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
    }

    // Modify urls   
    JSONArray websites = null;
    try {
        websites = contact.getJSONArray("websites");
        if (websites != null) {
            for (int i = 0; i < websites.length(); i++) {
                JSONObject website = (JSONObject) websites.get(i);
                String websiteId = getJsonString(website, "id");
                ;
                // This is a new website so do a DB insert
                if (websiteId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.Website.DATA,
                            getJsonString(website, "value"));
                    contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE,
                            getContactType(getJsonString(website, "type")));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing website so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(
                                    ContactsContract.CommonDataKinds.Website._ID + "=? AND "
                                            + ContactsContract.Data.MIMETYPE + "=?",
                                    new String[] { websiteId,
                                            ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.Website.DATA,
                                    getJsonString(website, "value"))
                            .withValue(ContactsContract.CommonDataKinds.Website.TYPE,
                                    getContactType(getJsonString(website, "type")))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get websites");
    }

    // Modify birthday
    String birthday = getJsonString(contact, "birthday");
    if (birthday != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
                                new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) })
                .withValue(ContactsContract.CommonDataKinds.Event.TYPE,
                        ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
                .withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
    }

    // Modify photos
    JSONArray photos = null;
    try {
        photos = contact.getJSONArray("photos");
        if (photos != null) {
            for (int i = 0; i < photos.length(); i++) {
                JSONObject photo = (JSONObject) photos.get(i);
                String photoId = getJsonString(photo, "id");
                byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
                // This is a new photo so do a DB insert
                if (photoId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
                    contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing photo so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.CommonDataKinds.Photo._ID + "=? AND "
                                    + ContactsContract.Data.MIMETYPE + "=?",
                            new String[] { photoId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
                            .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes).build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get photos");
    }

    boolean retVal = true;

    //Modify contact
    try {
        mApp.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    } catch (OperationApplicationException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    }

    return retVal;
}

From source file:org.zywx.wbpalmstar.plugin.uexcontacts.PFConcactMan.java

public static boolean add(Context context, Map content, Object accountType, Object accountName) {
    if (content == null || content.size() == 0) {
        return false;
    }//  w  w  w  . j a v a  2  s.c om
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
            .withValue(ContactsContract.RawContacts.AGGREGATION_MODE,
                    ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED)
            .build());

    for (int i = 0; i < EUExContact.types.length; i++) {

        String valuse = (String) content.get(EUExContact.types[i]);
        if (TextUtils.isEmpty(valuse)) {
            continue;
        }

        if (i == 0) {
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                            valuse.replaceAll(";", ""))
                    .build());
        }
        if (i == 1) {
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, valuse)
                    .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
                    .build());
        }
        if (i == 2) {
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Email.DATA, valuse)
                    .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                            ContactsContract.CommonDataKinds.Email.TYPE_HOME)
                    .build());
        }
        if (i == 3) {
            String[] structured = valuse.split(";");
            if (structured.length == 6) {
                String[] newstructured = new String[7];
                for (int j = 0; j < structured.length; j++) {
                    newstructured[j] = structured[j];
                }
                newstructured[6] = "";
                structured = newstructured;
            }
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, structured[6])
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, structured[5])
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, structured[4])
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, structured[3])
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                            structured[0] + structured[1] + structured[2])
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                            ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)
                    .build());
        }
        if (i == 4) {
            ops.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, valuse)
                    .withValue(ContactsContract.CommonDataKinds.Organization.TITLE,
                            (String) content.get(EUExContact.types[i + 1]))
                    .withValue(ContactsContract.CommonDataKinds.Organization.TYPE,
                            ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                    .build());

        }
        if (i == 6) {
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Website.URL, valuse)
                    .withValue(ContactsContract.CommonDataKinds.Website.TYPE,
                            ContactsContract.CommonDataKinds.Website.TYPE_WORK)
                    .build());
        }
        if (i == 7) {
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Note.NOTE, valuse).build());
        }
    }

    try {
        context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

    } catch (Exception e) {
        return false;
    }

    return true;
}