List of usage examples for android.content ContentProviderOperation newInsert
public static Builder newInsert(Uri uri)
From source file:com.gaba.alex.trafficincidents.Utility.java
private static ContentProviderOperation buildBatchOperation(JSONObject incident) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(IncidentsProvider.Incidents.CONTENT_URI); try {/*from w w w. java 2 s . c om*/ double lat = incident.getJSONObject(BING_JSON_POINT_KEY).getJSONArray(BING_JSON_COORDINATES_KEY) .getDouble(0); double lng = incident.getJSONObject(BING_JSON_POINT_KEY).getJSONArray(BING_JSON_COORDINATES_KEY) .getDouble(1); double toLat = incident.getJSONObject(BING_JSON_TO_POINT_KEY).getJSONArray(BING_JSON_COORDINATES_KEY) .getDouble(0); double toLng = incident.getJSONObject(BING_JSON_TO_POINT_KEY).getJSONArray(BING_JSON_COORDINATES_KEY) .getDouble(1); int type = incident.getInt(BING_JSON_TYPE_KEY); int severity = incident.getInt(BING_JSON_SEVERITY_KEY); String id = incident.getString(BING_JSON_INCIDENT_ID_KEY); String description = incident.getString(BING_JSON_DESCRIPTION_KEY); String roadClosed = incident.getString(BING_JSON_ROAD_CLOSED_KEY); String startDateMillis = incident.getString(BING_JSON_START_DATE_KEY); String endDateMillis = incident.getString(BING_JSON_END_DATE_KEY); startDateMillis = startDateMillis.substring(6, startDateMillis.length() - 2); endDateMillis = endDateMillis.substring(6, endDateMillis.length() - 2); builder.withValue(IncidentsColumns.LAT, lat); builder.withValue(IncidentsColumns.LNG, lng); builder.withValue(IncidentsColumns.TO_LAT, toLat); builder.withValue(IncidentsColumns.TO_LNG, toLng); builder.withValue(IncidentsColumns.TYPE, type); builder.withValue(IncidentsColumns.SEVERITY, severity); builder.withValue(IncidentsColumns._ID, id); builder.withValue(IncidentsColumns.DESCRIPTION, description); builder.withValue(IncidentsColumns.ROAD_CLOSED, roadClosed); builder.withValue(IncidentsColumns.START_DATE, startDateMillis); builder.withValue(IncidentsColumns.END_DATE, endDateMillis); } catch (JSONException e) { e.printStackTrace(); } return builder.build(); }
From source file:cz.maresmar.sfm.service.web.PortalsUpdateService.java
private static void updatePortalGroups(@NonNull Context context) throws IOException, UnsupportedApiException { Timber.i("Portal group update started"); URL url = new URL(ServerContract.PORTAL_GROUPS_SERVER_ADDRESS); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try (FirstLineInputStream fis = new FirstLineInputStream(urlConnection.getInputStream())) { SfmJsonPortalGroupResponse response = parseEntries(ServerContract.REPLY_TYPE_PORTAL_GROUPS, SfmJsonPortalGroupResponse.class, fis); ArrayList<ContentProviderOperation> operations = new ArrayList<>(); Uri portalGroupUri = ProviderContract.PortalGroup.getUri(); for (PortalGroupEntry portalGroupEntry : response.data) { operations.add(ContentProviderOperation.newInsert(portalGroupUri) .withValue(ProviderContract.PortalGroup._ID, portalGroupEntry.id) .withValue(ProviderContract.PortalGroup.NAME, portalGroupEntry.name) .withValue(ProviderContract.PortalGroup.DESCRIPTION, portalGroupEntry.description) .withYieldAllowed(true).build()); }/*from www. j ava 2s . c o m*/ // Apply them once for performance boost try { context.getContentResolver().applyBatch(ProviderContract.AUTHORITY, operations); } catch (OperationApplicationException e) { Timber.e(e, "Cannot save elements to db"); throw new UnsupportedOperationException("Cannot save elements to db ", e); } catch (RemoteException e) { Timber.e(e, "Cannot connect to db"); throw new RuntimeException("Cannot connect to db", e); } } finally { urlConnection.disconnect(); } }
From source file:at.bitfire.ical4android.AndroidTask.java
public Uri add() throws CalendarStorageException { BatchOperation batch = new BatchOperation(taskList.provider.client); Builder builder = ContentProviderOperation.newInsert(taskList.syncAdapterURI(taskList.provider.tasksUri())); buildTask(builder, false);/*from w w w .ja v a2 s . c o m*/ batch.enqueue(builder.build()); batch.commit(); return batch.getResult(0).uri; }
From source file:com.example.am.myapplication.ContactAdder.java
/** * Creates a contact entry from the current UI values in the account named by mSelectedAccount. *//* w w w . java 2s. co m*/ protected void createContactEntry() { // Get values from UI String name = mContactNameEditText.getText().toString(); String phone = mContactPhoneEditText.getText().toString(); String email = mContactEmailEditText.getText().toString(); int phoneType = mContactPhoneTypes.get(mContactPhoneTypeSpinner.getSelectedItemPosition()); int emailType = mContactEmailTypes.get(mContactEmailTypeSpinner.getSelectedItemPosition()); ; // Prepare contact creation request // // Note: We use RawContacts because this data must be associated with a particular account. // The system will aggregate this with any other data for this contact and create a // coresponding entry in the ContactsContract.Contacts provider for us. ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, mSelectedAccount.getType()) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, mSelectedAccount.getName()).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()); 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, phone) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, phoneType).build()); 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, email) .withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType).build()); // Ask the Contact provider to create a new contact Log.i(TAG, "Selected account: " + mSelectedAccount.getName() + " (" + mSelectedAccount.getType() + ")"); Log.i(TAG, "Creating contact: " + name); try { getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); } catch (Exception e) { // Display warning Context ctx = getApplicationContext(); CharSequence txt = getString(R.string.contactCreationFailure); int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(ctx, txt, duration); toast.show(); // Log exception Log.e(TAG, "Exceptoin encoutered while inserting contact: " + e); } }
From source file:com.chatwing.whitelabel.services.NotificationIntentService.java
private void insertNotificationMessagesToDb(Message[] messages) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); Uri notificationMessagesUri = ChatWingContentProvider.getNotificationMessagesUri(); ContentValues values;/*ww w . ja va 2 s.c o m*/ for (Message message : messages) { values = NotificationMessagesTable.getContentValues(message); batch.add(ContentProviderOperation.newInsert(notificationMessagesUri).withValues(values).build()); } try { getContentResolver().applyBatch(ChatWingContentProvider.AUTHORITY, batch); } catch (RemoteException e) { e.printStackTrace(); } catch (OperationApplicationException e) { e.printStackTrace(); } }
From source file:org.xwalk.runtime.extension.api.contacts.ContactSaver.java
public JSONObject save(String saveString) { mOps = new ArrayList<ContentProviderOperation>(); try {//w w w . j av a 2 s .c o m mContact = new JSONObject(saveString); } catch (JSONException e) { Log.e(TAG, "Failed to parse json data: " + e.toString()); return new JSONObject(); } mJson = new ContactJson(mContact); Builder builder = null; mId = mJson.getString("id"); mIsUpdate = mUtils.hasID(mId); Set<String> oldRawIds = null; if (!mIsUpdate) { // Create a null record for inserting later oldRawIds = mUtils.getCurrentRawIds(); mId = null; builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI); builder.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null); builder.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null); mOps.add(builder.build()); } // W3C Android //------------------------------------------------- // displayName StructuredName.display_name // honorificPrefixes StructuredName.prefix // givenNames StructuredName.given_name // additionalNames StructuredName.middle_name // familyNames StructuredName.family_name // honorificSuffixes StructuredName.suffix // nicknames Nickname.name if (mContact.has("name")) { final JSONObject name = mJson.getObject("name"); final ContactJson nameJson = new ContactJson(name); builder = newBuilder(StructuredName.CONTENT_ITEM_TYPE); builder.withValue(StructuredName.DISPLAY_NAME, nameJson.getString("displayName")); //FIXME(hdq): should read all names builder.withValue(StructuredName.FAMILY_NAME, nameJson.getFirstValue("familyNames")); builder.withValue(StructuredName.GIVEN_NAME, nameJson.getFirstValue("givenNames")); builder.withValue(StructuredName.MIDDLE_NAME, nameJson.getFirstValue("additionalNames")); builder.withValue(StructuredName.PREFIX, nameJson.getFirstValue("honorificPrefixes")); builder.withValue(StructuredName.SUFFIX, nameJson.getFirstValue("honorificSuffixes")); mOps.add(builder.build()); // Nickname belongs to another mimetype, so we need another builder for it. if (name.has("nicknames")) { builder = newBuilder(Nickname.CONTENT_ITEM_TYPE); builder.withValue(Nickname.NAME, nameJson.getFirstValue("nicknames")); mOps.add(builder.build()); } } if (mContact.has("categories")) { List<String> groupIds = new ArrayList<String>(); for (String groupTitle : mJson.getStringArray("categories")) { groupIds.add(mUtils.getEnsuredGroupId(groupTitle)); } buildByArray(GroupMembership.CONTENT_ITEM_TYPE, GroupMembership.GROUP_ROW_ID, groupIds); } if (mContact.has("gender")) { final String gender = mJson.getString("gender"); if (Arrays.asList("male", "female", "other", "none", "unknown").contains(gender)) { builder = newBuilder(ContactConstants.CUSTOM_MIMETYPE_GENDER); builder.withValue(Data.DATA1, gender); mOps.add(builder.build()); } } buildByDate("lastUpdated", ContactConstants.CUSTOM_MIMETYPE_LASTUPDATED, Data.DATA1); buildByEvent("birthday", Event.TYPE_BIRTHDAY); buildByEvent("anniversary", Event.TYPE_ANNIVERSARY); buildByContactMapList(); // Perform the operation batch try { mUtils.mResolver.applyBatch(ContactsContract.AUTHORITY, mOps); } catch (Exception e) { if (e instanceof RemoteException || e instanceof OperationApplicationException || e instanceof SecurityException) { Log.e(TAG, "Failed to apply batch: " + e.toString()); return new JSONObject(); } else { throw new RuntimeException(e); } } // If it is a new contact, need to get and return its auto-generated id. if (!mIsUpdate) { Set<String> newRawIds = mUtils.getCurrentRawIds(); if (newRawIds == null) return new JSONObject(); newRawIds.removeAll(oldRawIds); if (newRawIds.size() != 1) { Log.e(TAG, "Something wrong after batch applied, " + "new raw ids are: " + newRawIds.toString()); return mContact; } String id = mUtils.getId(newRawIds.iterator().next()); PutToContact(id); } return mContact; }
From source file:com.barak.pix.FeedsActivity.java
/** * This method add my account under IM field at default Contact * application/*from w w w . j a v a2 s. co m*/ * * Labeled with my custom protocol. * * @param contentResolver * content resolver * @param uid * User id from android * @param account * account name */ public static void updateIMContactField(ContentResolver contentResolver, String uid, String account) { ContentValues contentValues = new ContentValues(); contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, Integer.parseInt(uid)); contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE); contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE, ContactsContract.CommonDataKinds.Im.TYPE_CUSTOM); contentValues.put(ContactsContract.CommonDataKinds.Im.LABEL, IM_LABEL); contentValues.put(ContactsContract.CommonDataKinds.Im.PROTOCOL, ContactsContract.CommonDataKinds.Im.PROTOCOL_CUSTOM); contentValues.put(ContactsContract.CommonDataKinds.Im.CUSTOM_PROTOCOL, IM_LABEL); contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, account); ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues) .build()); try { contentResolver.applyBatch(ContactsContract.AUTHORITY, ops); } catch (Exception e) { Log.d(LOG_TAG, "Can't update Contact's IM field."); } }
From source file:saschpe.birthdays.service.CalendarSyncService.java
/** * Syncing work-horse./*from w w w . j a v a 2 s .c o m*/ * * Simply runs in current thread if invoked directly. */ public static void performSync(Context context) { Log.d(TAG, "Perform sync..."); ContentResolver cr = context.getContentResolver(); if (cr == null) { Log.e(TAG, "Unable to get content resolver!"); return; } long calendarId = getCalendar(context); int deletedRows = cr.delete(getCalendarUri(context, CalendarContract.Events.CONTENT_URI), CalendarContract.Events.CALENDAR_ID + " = ?", new String[] { String.valueOf(calendarId) }); Log.i(TAG, "Removed " + deletedRows + " rows from calendar " + calendarId); final long[] reminderMinutes = PreferencesHelper.getReminderMinutes(context); ArrayList<ContentProviderOperation> operations = new ArrayList<>(); Cursor cursor = getContactsEvents(context, cr); if (cursor == null) { Log.e(TAG, "Failed to parse contacts events"); } try { final int eventDateColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE); final int displayNameColumn = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); final int eventTypeColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE); final int eventCustomLabelColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.LABEL); final int eventLookupKeyColumn = cursor .getColumnIndex(ContactsContract.CommonDataKinds.Event.LOOKUP_KEY); int backRef = 0; // Loop over all events while (cursor != null && cursor.moveToNext()) { final String eventDateString = cursor.getString(eventDateColumn); final String displayName = cursor.getString(displayNameColumn); final int eventType = cursor.getInt(eventTypeColumn); final String eventLookupKey = cursor.getString(eventLookupKeyColumn); final Date eventDate = parseEventDateString(eventDateString); if (eventDate != null) { // Get year from event Calendar eventCalendar = Calendar.getInstance(); eventCalendar.setTime(eventDate); int eventYear = eventCalendar.get(Calendar.YEAR); //Log.debug("Event year: " + eventYear); // If year < 1800 don't show brackets with age behind name. When no year is defined // parseEventDateString() sets it to 1700. Also iCloud for example sets year to // 1604 if no year is defined in their user interface. boolean hasYear = false; if (eventYear >= 1800) { hasYear = true; } // Get current year Calendar currentCalendar = Calendar.getInstance(); final int currentYear = currentCalendar.get(Calendar.YEAR); // Insert events for the past 2 years and the next 5 years. Events are not inserted // as recurring events to have different titles with birthday age in it. final int startYear = currentYear - 1; final int endYear = currentYear + 3; for (int year = startYear; year <= endYear; year++) { // Calculate age final int age = year - eventYear; // If birthday has year and age of this event >= 0, display age in title boolean includeAge = false; if (hasYear && age >= 0) { includeAge = true; } //Log.debug("Year: " + year + " age: " + age + " include age: " + includeAge); String title = null; String description = ""; if (displayName != null) { switch (eventType) { case ContactsContract.CommonDataKinds.Event.TYPE_CUSTOM: String eventCustomLabel = cursor.getString(eventCustomLabelColumn); if (eventCustomLabel != null) { title = context.getString(R.string.event_custom_title_template, displayName, eventCustomLabel); } else { title = context.getString(R.string.event_other_title_template, displayName); } break; case ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY: title = context.getString(R.string.event_anniversary_title_template, displayName); if (age == 1) { description = context.getString( R.string.event_anniversary_description_singular_template, displayName, age); } else { description = context.getString( R.string.event_anniversary_description_plural_template, displayName, age); } break; case ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY: title = context.getString(R.string.event_birthday_title_template, displayName); if (age == 1) { description = context.getString( R.string.event_birthday_description_singular_template, displayName, eventYear, age); } else { description = context.getString( R.string.event_birthday_description_plural_template, displayName, eventYear, age); } break; default: // Includes ContactsContract.CommonDataKinds.Event.TYPE_OTHER title = String.format(context.getString(R.string.event_other_title_template), displayName); break; } } if (title != null) { Log.d(TAG, "Title: " + title + " backref: " + backRef); operations.add(insertEvent(context, calendarId, eventDate, year, title, description, eventLookupKey)); // Gets ContentProviderOperation to insert new reminder to the ContentProviderOperation // with the given backRef. This is done using "withValueBackReference" int reminderOperations = 0; for (long reminderMinute : reminderMinutes) { if (reminderMinute >= -1) { ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert( getCalendarUri(context, CalendarContract.Reminders.CONTENT_URI)); // Add reminder to last added event identified by backRef // see http://stackoverflow.com/questions/4655291/semantics-of-withvaluebackreference builder.withValueBackReference(CalendarContract.Reminders.EVENT_ID, backRef); builder.withValue(CalendarContract.Reminders.MINUTES, reminderMinute); builder.withValue(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT); operations.add(builder.build()); reminderOperations += 1; } } // Back reference for the next reminders, 1 is for the event backRef += 1 + reminderOperations; } else { Log.d(TAG, "Event title empty, won't insert event and reminder"); } // Intermediate commit, otherwise the binder transaction fails on large operation list if (operations.size() > 200) { applyBatchOperation(cr, operations); backRef = 0; operations.clear(); } } } } } finally { if (cursor != null && !cursor.isClosed()) cursor.close(); } // Create remaining events (that haven't been created by intermediate commits): if (operations.size() > 0) { applyBatchOperation(cr, operations); } LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(ACTION_SYNC_DONE)); Log.d(TAG, "Done performing sync..."); }
From source file:org.mythtv.service.channel.v25.ChannelHelperV25.java
public void processChannel(final Context context, final LocationProfile locationProfile, ArrayList<ContentProviderOperation> ops, ChannelInfo channel) { // Log.d( TAG, "processChannel : enter" ); if (channel.getSourceId() < 1 || (null == channel.getXMLTVID() || "".equals(channel.getXMLTVID()))) { Log.d(TAG,/*from ww w. java 2 s. c o m*/ "processChannel : channelId=" + channel.getChanId() + ", channelNumber=" + channel.getChanNum() + ", callSign=" + channel.getCallSign() + ", sourceId=" + channel.getSourceId() + ", xmltvid=" + channel.getXMLTVID()); } ContentValues channelValues = convertChannelInfoToContentValues(locationProfile, channel); ops.add(ContentProviderOperation.newInsert(ChannelConstants.CONTENT_URI).withValues(channelValues) .withYieldAllowed(true).build()); // Log.d( TAG, "processChannel : exit" ); }
From source file:org.codarama.haxsync.services.ContactsSyncAdapterService.java
private static void updateContactStatus(long rawContactId, String status, long timeStamp) { if (status != null && timeStamp != 0) { ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId); Uri entityUri = Uri.withAppendedPath(rawContactUri, Entity.CONTENT_DIRECTORY); Cursor c = mContentResolver.query(entityUri, new String[] { RawContacts.SOURCE_ID, Entity.DATA_ID, Entity.MIMETYPE, Entity.DATA1 }, null, null, null);//from www. jav a 2s . c om try { while (c.moveToNext()) { if (!c.isNull(1)) { String mimeType = c.getString(2); if (mimeType.equals("vnd.android.cursor.item/vnd.org.codarama.haxsync.profile")) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ContactsContract.StatusUpdates.CONTENT_URI); builder.withValue(ContactsContract.StatusUpdates.DATA_ID, c.getLong(1)); builder.withValue(ContactsContract.StatusUpdates.STATUS, status); builder.withValue(ContactsContract.StatusUpdates.STATUS_RES_PACKAGE, "org.codarama.haxsync"); builder.withValue(ContactsContract.StatusUpdates.STATUS_LABEL, R.string.app_name); builder.withValue(ContactsContract.StatusUpdates.STATUS_ICON, R.drawable.icon); builder.withValue(ContactsContract.StatusUpdates.STATUS_TIMESTAMP, timeStamp); operationList.add(builder.build()); } } } } finally { c.close(); } try { mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList); } catch (RemoteException e) { Log.e("Error", e.getLocalizedMessage()); } catch (OperationApplicationException e) { Log.e("Error", e.getLocalizedMessage()); } } }