List of usage examples for android.content ContentProviderOperation newUpdate
public static Builder newUpdate(Uri uri)
From source file:es.example.contacts.ui.ContactDetailFragment.java
/** * Builds an address LinearLayout based on address information from the Contacts Provider. * Each address for the contact gets its own LinearLayout object; for example, if the contact * has three postal addresses, then 3 LinearLayouts are generated. * * @param addressType From//w w w . ja v a 2 s . c o m * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#TYPE} * @param addressTypeLabel From * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#LABEL} * @param address From * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#FORMATTED_ADDRESS} * @param phone From * {@link android.provider.ContactsContract.CommonDataKinds.Phone#NUMBER} * @param data1 From * {@link android.provider.ContactsContract.Data#DATA1} * @param _id From * {@link android.provider.ContactsContract#} * @return A LinearLayout to add to the contact details layout, * populated with the provided address details. */ private LinearLayout buildAddressLayout(int addressType, String addressTypeLabel, final String address, final String phone, final String data1, final String _id, final String _name) { // Inflates the address layout final LinearLayout addressLayout = (LinearLayout) LayoutInflater.from(getActivity()) .inflate(R.layout.contact_detail_item, mDetailsLayout, false); // Gets handles to the view objects in the layout final TextView headerTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_header); final TextView addressTextView = (TextView) addressLayout.findViewById(R.id.contact_detail_item); final ImageButton viewAddressButton = (ImageButton) addressLayout.findViewById(R.id.button_view_address); final TextView phoneTextView = (TextView) addressLayout.findViewById(R.id.contact_phone); final SeekBar levelSeekBar = (SeekBar) addressLayout.findViewById(R.id.contact_level); final ImageButton saveButton = (ImageButton) addressLayout.findViewById(R.id.button_save); Integer prioridad = Integer.parseInt(data1 == null ? "4" : data1); // If there's no addresses for the contact, shows the empty view and message, and hides the // header and button. if (addressTypeLabel == null && addressType == 0 && phone == null) { headerTextView.setVisibility(View.GONE); viewAddressButton.setVisibility(View.GONE); addressTextView.setText(R.string.no_address); } else { // Gets postal address label type CharSequence label = StructuredPostal.getTypeLabel(getResources(), addressType, addressTypeLabel); // Sets TextView objects in the layout headerTextView.setText(label); addressTextView.setText(address); phoneTextView.setText(phone); levelSeekBar.setProgress(prioridad); // Defines an onClickListener object for the address button viewAddressButton.setOnClickListener(new View.OnClickListener() { // Defines what to do when users click the address button @Override public void onClick(View view) { final Intent viewIntent = new Intent(Intent.ACTION_VIEW, constructGeoUri(address)); // A PackageManager instance is needed to verify that there's a default app // that handles ACTION_VIEW and a geo Uri. final PackageManager packageManager = getActivity().getPackageManager(); // Checks for an activity that can handle this intent. Preferred in this // case over Intent.createChooser() as it will still let the user choose // a default (or use a previously set default) for geo Uris. if (packageManager.resolveActivity(viewIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) { startActivity(viewIntent); } else { // If no default is found, displays a message that no activity can handle // the view button. Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show(); } } }); // Defines an onClickListener object for the save button saveButton.setOnClickListener(new View.OnClickListener() { // Defines what to do when users click the address button @Override public void onClick(View view) { // Creates a new intent for sending to the device's contacts application // Creates a new array of ContentProviderOperation objects. ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); Integer prioridad = levelSeekBar.getProgress(); Log.d("ContactDetalFragment", _id); ContentProviderOperation.Builder op; if (data1 == null) { Uri uri = addCallerIsSyncAdapterParameter(Data.CONTENT_URI, true); ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build()); 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, _name) .build()); op = ContentProviderOperation.newInsert(Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) .withValue(Data.DATA1, prioridad).withValue(Data.MIMETYPE, LEVEL_MIME_TYPE); } else { String where = Data.MIMETYPE + " = ? "; String[] params = new String[] { LEVEL_MIME_TYPE, }; op = ContentProviderOperation.newUpdate(Data.CONTENT_URI).withSelection(where, params) .withValue(Data.DATA1, prioridad); } ops.add(op.build()); try { ContentProviderResult[] results = view.getContext().getContentResolver() .applyBatch(ContactsContract.AUTHORITY, ops); } catch (Exception e) { CharSequence txt = getString(R.string.contactUpdateFailure); int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(view.getContext(), txt, duration); toast.show(); // Log exception Log.e(TAG, "Exception encountered while inserting contact: " + e); } } }); } return addressLayout; }
From source file:id.ridon.keude.UpdateService.java
private ContentProviderOperation updateExistingApp(App app) { Uri uri = AppProvider.getContentUri(app); ContentValues values = app.toContentValues(); for (String toIgnore : APP_FIELDS_TO_IGNORE) { if (values.containsKey(toIgnore)) { values.remove(toIgnore);// w w w . ja v a 2 s.com } } return ContentProviderOperation.newUpdate(uri).withValues(values).build(); }
From source file:com.murrayc.galaxyzoo.app.QuestionFragment.java
/** * Avoid calling this from the main (UI) thread - StrictMode doesn't like it on at least API 15 * and API 16./*from w w w .j a v a 2s .c om*/ * * @param classificationInProgress */ private void saveClassificationSync(final ClassificationInProgress classificationInProgress) { final String itemId = getItemId(); if (TextUtils.equals(itemId, ItemsContentProvider.URI_PART_ITEM_ID_NEXT)) { Log.error("QuestionFragment.saveClassification(): Attempting to save with the 'next' ID."); return; } final Activity activity = getActivity(); if (activity == null) return; final ContentResolver resolver = activity.getContentResolver(); // Add the related Classification Answers: // Use a ContentProvider operation to perform operations together, // either completely or not at all, as a transaction. // This should prevent an incomplete classification from being uploaded // before we have finished adding it. // // We use the specific ArrayList<> subtype instead of List<> because // ContentResolver.applyBatch() takes an ArrayList for some reason. final ArrayList<ContentProviderOperation> ops = new ArrayList<>(); int sequence = 0; final List<ClassificationInProgress.QuestionAnswer> answers = classificationInProgress.getAnswers(); if (answers != null) { for (final ClassificationInProgress.QuestionAnswer answer : answers) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ClassificationAnswer.CLASSIFICATION_ANSWERS_URI); final ContentValues valuesAnswers = new ContentValues(); valuesAnswers.put(ClassificationAnswer.Columns.ITEM_ID, itemId); valuesAnswers.put(ClassificationAnswer.Columns.SEQUENCE, sequence); valuesAnswers.put(ClassificationAnswer.Columns.QUESTION_ID, answer.getQuestionId()); valuesAnswers.put(ClassificationAnswer.Columns.ANSWER_ID, answer.getAnswerId()); builder.withValues(valuesAnswers); ops.add(builder.build()); //For instance, if the question has multiple-choice checkboxes to select before clicking //the "Done" answer: final List<String> checkboxIds = answer.getCheckboxIds(); if (checkboxIds != null) { for (final String checkboxId : checkboxIds) { builder = ContentProviderOperation .newInsert(ClassificationCheckbox.CLASSIFICATION_CHECKBOXES_URI); final ContentValues valuesCheckbox = new ContentValues(); valuesCheckbox.put(ClassificationCheckbox.Columns.ITEM_ID, itemId); valuesCheckbox.put(ClassificationCheckbox.Columns.SEQUENCE, sequence); valuesCheckbox.put(ClassificationCheckbox.Columns.QUESTION_ID, answer.getQuestionId()); valuesCheckbox.put(ClassificationCheckbox.Columns.CHECKBOX_ID, checkboxId); builder.withValues(valuesCheckbox); ops.add(builder.build()); } } sequence++; } } //Mark the Item (Subject) as done: final Uri.Builder uriBuilder = Item.ITEMS_URI.buildUpon(); uriBuilder.appendPath(getItemId()); final ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(uriBuilder.build()); final ContentValues values = new ContentValues(); values.put(Item.Columns.DONE, true); values.put(Item.Columns.DATETIME_DONE, getCurrentDateTimeAsIso8601()); values.put(Item.Columns.FAVORITE, classificationInProgress.isFavorite()); builder.withValues(values); ops.add(builder.build()); try { resolver.applyBatch(ClassificationAnswer.AUTHORITY, ops); } catch (final RemoteException | OperationApplicationException e) { //This should never happen, and would mean a loss of the current classification, //so let it crash the app and generate a report with a stacktrace, //because that's (slightly) better than just ignoring it. // //I guess that OperationApplicationException is not an unchecked exception, //because it could be caused by not just pure programmer error, //for instance if our data did not fulfill a Sqlite database constraint. Log.error("QuestionFragment. saveClassification(): Exception from applyBatch()", e); throw new RuntimeException("ContentResolver.applyBatch() failed.", e); } //The ItemsContentProvider will upload the classification later. }
From source file:org.sufficientlysecure.keychain.util.ContactHelper.java
private ContentProviderOperation.Builder insertOrUpdateForRawContact(Uri uri, long rawContactId, String itemType) {// w ww . j av a 2s . c om if (rawContactId == -1) { return referenceRawContact(ContentProviderOperation.newInsert(uri), rawContactId) .withValue(ContactsContract.Data.MIMETYPE, itemType); } else { return selectByRawContactAndItemType(ContentProviderOperation.newUpdate(uri), rawContactId, itemType); } }
From source file:net.ddns.mlsoftlaberge.contactslist.ui.ContactAdminFragment.java
private void updatenote() { normalizememo();// w w w . j a va2 s .c om 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:com.owncloud.android.datamodel.FileDataStorageManager.java
/** * Updates database and file system for a file or folder that was moved to a different location. * * TODO explore better (faster) implementations * TODO throw exceptions up !//from ww w . j a v a 2 s . c o m */ public void moveLocalFile(OCFile file, String targetPath, String targetParentPath) { if (file != null && file.fileExists() && !OCFile.ROOT_PATH.equals(file.getFileName())) { OCFile targetParent = getFileByPath(targetParentPath); if (targetParent == null) { throw new IllegalStateException("Parent folder of the target path does not exist!!"); } /// 1. get all the descendants of the moved element in a single QUERY Cursor c = null; if (getContentProviderClient() != null) { try { c = getContentProviderClient().query(ProviderTableMeta.CONTENT_URI, null, ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ? ", new String[] { mAccount.name, file.getRemotePath() + "%" }, ProviderTableMeta.FILE_PATH + " ASC "); } catch (RemoteException e) { Log_OC.e(TAG, e.getMessage()); } } else { c = getContentResolver().query(ProviderTableMeta.CONTENT_URI, null, ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ? ", new String[] { mAccount.name, file.getRemotePath() + "%" }, ProviderTableMeta.FILE_PATH + " ASC "); } List<String> originalPathsToTriggerMediaScan = new ArrayList<>(); List<String> newPathsToTriggerMediaScan = new ArrayList<>(); String defaultSavePath = FileStorageUtils.getSavePath(mAccount.name); /// 2. prepare a batch of update operations to change all the descendants if (c != null) { ArrayList<ContentProviderOperation> operations = new ArrayList<>(c.getCount()); if (c.moveToFirst()) { int lengthOfOldPath = file.getRemotePath().length(); int lengthOfOldStoragePath = defaultSavePath.length() + lengthOfOldPath; do { ContentValues cv = new ContentValues(); // keep construction in the loop OCFile child = createFileInstance(c); cv.put(ProviderTableMeta.FILE_PATH, targetPath + child.getRemotePath().substring(lengthOfOldPath)); if (child.getStoragePath() != null && child.getStoragePath().startsWith(defaultSavePath)) { // update link to downloaded content - but local move is not done here! String targetLocalPath = defaultSavePath + targetPath + child.getStoragePath().substring(lengthOfOldStoragePath); cv.put(ProviderTableMeta.FILE_STORAGE_PATH, targetLocalPath); originalPathsToTriggerMediaScan.add(child.getStoragePath()); newPathsToTriggerMediaScan.add(targetLocalPath); } if (targetParent .getAvailableOfflineStatus() != OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE) { // moving to an available offline subfolder cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT.getValue()); } else { // moving to a not available offline subfolder - with care if (file.getAvailableOfflineStatus() == OCFile.AvailableOfflineStatus.AVAILABLE_OFFLINE_PARENT) { cv.put(ProviderTableMeta.FILE_KEEP_IN_SYNC, OCFile.AvailableOfflineStatus.NOT_AVAILABLE_OFFLINE.getValue()); } } if (child.getRemotePath().equals(file.getRemotePath())) { cv.put(ProviderTableMeta.FILE_PARENT, targetParent.getFileId()); } operations.add(ContentProviderOperation.newUpdate(ProviderTableMeta.CONTENT_URI) .withValues(cv).withSelection(ProviderTableMeta._ID + "=?", new String[] { String.valueOf(child.getFileId()) }) .build()); } while (c.moveToNext()); } c.close(); /// 3. apply updates in batch try { if (getContentResolver() != null) { getContentResolver().applyBatch(MainApp.getAuthority(), operations); } else { getContentProviderClient().applyBatch(operations); } } catch (Exception e) { Log_OC.e(TAG, "Fail to update " + file.getFileId() + " and descendants in database", e); } } /// 4. move in local file system String originalLocalPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file); String targetLocalPath = defaultSavePath + targetPath; File localFile = new File(originalLocalPath); boolean renamed = false; if (localFile.exists()) { File targetFile = new File(targetLocalPath); File targetFolder = targetFile.getParentFile(); if (!targetFolder.exists()) { targetFolder.mkdirs(); } renamed = localFile.renameTo(targetFile); } if (renamed) { Iterator<String> it = originalPathsToTriggerMediaScan.iterator(); while (it.hasNext()) { // Notify MediaScanner about removed file deleteFileInMediaScan(it.next()); } it = newPathsToTriggerMediaScan.iterator(); while (it.hasNext()) { // Notify MediaScanner about new file/folder triggerMediaScan(it.next()); } } } }
From source file:com.phonegap.ContactAccessorSdk5.java
/** * Creates a new contact and stores it in the database * /*from w w w. j av a2 s . c om*/ * @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.linphone.ContactsManager.java
public void updateExistingContact(ArrayList<ContentProviderOperation> ops, Contact contact, String firstName, String lastName) {//from w w w .j a v a 2 s .com if (getDisplayName(lastName, firstName) != null) { String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'"; String[] args = new String[] { String.valueOf(contact.getID()) }; ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI) .withSelection(select, args) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, lastName) .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, firstName).build()); } }
From source file:org.linphone.ContactsManager.java
public void updateExistingContactPicture(ArrayList<ContentProviderOperation> ops, Contact contact, String path) {// ww w.j a va 2 s . co m String select = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "='" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'"; String[] args = new String[] { String.valueOf(contact.getID()) }; ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(select, args) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO_FILE_ID, path) //.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO_FILE_ID, ) .build()); }
From source file:com.karura.framework.plugins.utils.ContactAccessorSdk5.java
/** * Creates a new contact and stores it in the database * /* w w w . ja v a2s . 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 String modifyContact(String id, JSONObject contact, String accountType, String accountName) { // 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 = Integer.valueOf(getJsonString(contact, "rawId")); // 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, accountType) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName).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) { // Delete all the phones if (phones.length() == 0) { ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection( ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE }) .build()); } // Modify or add a phone else { 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) { // Delete all the emails if (emails.length() == 0) { ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection( ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }) .build()); } // Modify or add a email else { 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) { // Delete all the addresses if (addresses.length() == 0) { ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI) .withSelection( ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE }) .build()); } // Modify or add a address else { 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.TYPE, getAddressType(getJsonString(address, "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.TYPE, getAddressType(getJsonString(address, "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) { // Delete all the organizations if (organizations.length() == 0) { ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI) .withSelection( ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE }) .build()); } // Modify or add a organization else { 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.TYPE, getOrgType(getJsonString(org, "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.TYPE, getOrgType(getJsonString(org, "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) { // Delete all the ims if (ims.length() == 0) { ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection( ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE }) .build()); } // Modify or add a im else { 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, getImType(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("urls"); if (websites != null) { // Delete all the websites if (websites.length() == 0) { Log.d(LOG_TAG, "This means we should be deleting all the phone numbers."); ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection( ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE }) .build()); } // Modify or add a website else { 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) { // Delete all the photos if (photos.length() == 0) { ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection( ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE }) .build()); } // Modify or add a photo else { 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 { getContext().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; } // if the save was a success return the contact ID if (retVal) { return id; } else { return null; } }