List of usage examples for android.net Uri getLastPathSegment
@Nullable public abstract String getLastPathSegment();
From source file:com.nextgis.maplibui.service.TrackerService.java
private void startTrack() { // get track name date unique appendix final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd--HH-mm-ss", Locale.getDefault()); // insert DB row final long started = System.currentTimeMillis(); String mTrackName = simpleDateFormat.format(started); mValues.clear();//from w w w .java 2s . c o m mValues.put(TrackLayer.FIELD_NAME, mTrackName); mValues.put(TrackLayer.FIELD_START, started); mValues.put(TrackLayer.FIELD_VISIBLE, true); Uri newTrack = getContentResolver().insert(mContentUriTracks, mValues); if (null != newTrack) { // save vars mTrackId = newTrack.getLastPathSegment(); mSharedPreferencesTemp.edit().putString(TRACK_URI, newTrack.toString()).commit(); } mIsRunning = true; addSplitter(); }
From source file:org.kontalk.ui.ConversationsActivity.java
private void startGroupChat(List<Uri> users) { String selfJid = Authenticator.getSelfJID(this); String groupId = StringUtils.randomString(20); String groupJid = KontalkGroupCommands.createGroupJid(groupId, selfJid); // ensure no duplicates Set<String> usersList = new HashSet<>(); for (Uri uri : users) { String member = uri.getLastPathSegment(); // exclude ourselves if (!member.equalsIgnoreCase(selfJid)) usersList.add(member);/* w w w . j av a 2 s. c o m*/ } if (usersList.size() > 0) { askGroupSubject(usersList, groupJid); } }
From source file:com.keithandthegirl.services.download.DownloadService.java
@TargetApi(8) @Override// w w w.j a v a2 s . c o m protected void onHandleIntent(Intent requestIntent) { Log.v(TAG, "onHandleIntent : enter"); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mOriginalRequestIntent = requestIntent; Resource resourceType = Resource.valueOf(requestIntent.getStringExtra(RESOURCE_TYPE_EXTRA)); mCallback = requestIntent.getParcelableExtra(SERVICE_CALLBACK); Uri data = requestIntent.getData(); String urlPath = requestIntent.getStringExtra("urlpath"); String directory = requestIntent.getStringExtra("directory"); String filename = data.getLastPathSegment(); File root; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { switch (resourceType) { case MP3: root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS); break; case MP4: root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); break; case M4V: root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); break; case JPG: root = getExternalCacheDir(); filename = requestIntent.getLongExtra("id", -1) + ".jpg"; break; default: root = getExternalCacheDir(); break; } } else { root = Environment.getExternalStorageDirectory(); } File outputDir = new File(root, directory); outputDir.mkdirs(); File output = new File(outputDir, filename); if (output.exists()) { result = FragmentActivity.RESULT_OK; mCallback.send(result, getOriginalIntentBundle()); Log.v(TAG, "onHandleIntent : exit, image exists"); return; } switch (resourceType) { case MP3: Log.v(TAG, "onHandleIntent : saving mp3"); savePodcast(requestIntent.getLongExtra("id", -1), requestIntent.getStringExtra("title"), urlPath, output); mCallback.send(result, getOriginalIntentBundle()); break; case MP4: Log.v(TAG, "onHandleIntent : saving mp4"); savePodcast(requestIntent.getLongExtra("id", -1), requestIntent.getStringExtra("title"), urlPath, output); mCallback.send(result, getOriginalIntentBundle()); break; case M4V: Log.v(TAG, "onHandleIntent : saving m4v"); savePodcast(requestIntent.getLongExtra("id", -1), requestIntent.getStringExtra("title"), urlPath, output); mCallback.send(result, getOriginalIntentBundle()); break; case JPG: Log.v(TAG, "onHandleIntent : saving jpg"); saveBitmap(requestIntent.getStringExtra("filename"), urlPath, output); mCallback.send(result, getOriginalIntentBundle()); break; default: Log.w(TAG, "onHandleIntent : unknown extension '" + resourceType.getExtension() + "'"); mCallback.send(REQUEST_INVALID, getOriginalIntentBundle()); break; } Log.v(TAG, "onHandleIntent : exit"); }
From source file:com.musenkishi.wally.fragments.RandomImagesFragment.java
@Override public boolean handleMessage(Message msg) { switch (msg.what) { case MSG_GET_IMAGES: final int index = msg.arg1; WallyApplication.getDataProviderInstance().getImages(NetworkDataProvider.PATH_RANDOM, index, WallyApplication.getFilterSettings(), new DataProvider.OnImagesReceivedListener() { @Override/*w w w . j a va 2 s .com*/ public void onImagesReceived(ArrayList<Image> images) { Message msgObj = uiHandler.obtainMessage(); msgObj.what = index == 1 ? MSG_IMAGES_REQUEST_CREATE : MSG_IMAGES_REQUEST_APPEND; msgObj.obj = images; uiHandler.sendMessage(msgObj); } @Override public void onError(DataProviderError dataProviderError) { showError(dataProviderError, index); } }); break; case MSG_SAVE_BUTTON_CLICKED: Image image = (Image) msg.obj; WallyApplication.getDataProviderInstance().getPageData(image.imagePageURL(), new DataProvider.OnPageReceivedListener() { @Override public void onPageReceived(ImagePage imagePage) { Message msgImagePage = uiHandler.obtainMessage(); msgImagePage.what = MSG_PAGE_RECEIVED; msgImagePage.obj = imagePage; uiHandler.sendMessage(msgImagePage); } @Override public void onError(DataProviderError dataProviderError) { Message msgObj = uiHandler.obtainMessage(); msgObj.what = MSG_ERROR_IMAGE_SAVING; msgObj.obj = dataProviderError; uiHandler.sendMessage(msgObj); } }); break; case MSG_PAGE_RECEIVED: ImagePage imagePage = (ImagePage) msg.obj; if (imagePage != null) { SaveImageRequest saveImageRequest = WallyApplication.getDataProviderInstance() .downloadImageIfNeeded(imagePage.imagePath(), imagePage.imageId(), getResources().getString(R.string.notification_title_image_saving)); if (saveImageRequest.getDownloadID() != null && getActivity() instanceof MainActivity) { WallyApplication.getDownloadIDs().put(saveImageRequest.getDownloadID(), imagePage.imageId()); } else { onFileChange(); } } break; case MSG_ERROR_IMAGE_REQUEST: if (getActivity() != null) { DataProviderError dataProviderError = (DataProviderError) msg.obj; int imagesIndex = msg.arg1; showErrorMessage(dataProviderError, imagesIndex); } break; case MSG_ERROR_IMAGE_SAVING: if (getActivity() != null) { NotificationProvider notificationProvider = new NotificationProvider(); notificationProvider.cancelAll(getActivity()); Toast.makeText(getActivity(), "Couldn't save image", Toast.LENGTH_SHORT).show(); } break; case MSG_IMAGES_REQUEST_CREATE: ArrayList<Image> images = (ArrayList<Image>) msg.obj; boolean shouldScheduleLayoutAnimation = msg.arg1 == 0; isLoading = false; if (images != null) { hideLoader(); imagesAdapter = new RecyclerImagesAdapter(images, itemSize); imagesAdapter.setOnSaveButtonClickedListener(RandomImagesFragment.this); imagesAdapter.updateSavedFilesList(savedFiles); gridView.setAdapter(imagesAdapter); setupAdapter(); if (shouldScheduleLayoutAnimation) { gridView.scheduleLayoutAnimation(); } } break; case MSG_IMAGES_REQUEST_APPEND: ArrayList<Image> extraImages = (ArrayList<Image>) msg.obj; isLoading = false; if (extraImages != null) { hideLoader(); int endPosition = imagesAdapter.getItemCount(); ArrayList<Image> currentList = imagesAdapter.getImages(); currentList.addAll(extraImages); imagesAdapter.notifyItemRangeInserted(endPosition, extraImages.size()); } break; case MSG_GET_LIST_OF_SAVED_IMAGES: HashMap<String, Boolean> existingFiles = new HashMap<String, Boolean>(); FileManager fileManager = new FileManager(); for (Uri uri : fileManager.getFiles()) { String filename = uri.getLastPathSegment(); String[] filenames = filename.split("\\.(?=[^\\.]+$)"); //split filename from it's extension existingFiles.put(filenames[0], true); } Message fileListMessage = uiHandler.obtainMessage(); fileListMessage.obj = existingFiles; fileListMessage.what = MSG_SAVE_LIST_OF_SAVED_IMAGES; uiHandler.sendMessage(fileListMessage); break; case MSG_SAVE_LIST_OF_SAVED_IMAGES: savedFiles = (HashMap<String, Boolean>) msg.obj; if (imagesAdapter != null) { imagesAdapter.updateSavedFilesList(savedFiles); imagesAdapter.notifySavedItemsChanged(); } break; } return false; }
From source file:com.app.encontreibvrr.uploadImagem.MainActivityStorage.java
private void uploadFromUri(Uri fileUri) { Log.d(TAG, "uploadFromUri:src:" + fileUri.toString()); // [START get_child_ref] // Get a reference to store file at photos/<FILENAME>.jpg final StorageReference photoRef = mStorageRef.child("photos").child(fileUri.getLastPathSegment()); // [END get_child_ref] // Upload file to Firebase Storage // [START_EXCLUDE] showProgressDialog();// w w w . ja v a 2s .c om // [END_EXCLUDE] Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath()); photoRef.putFile(fileUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // Upload succeeded Log.d(TAG, "uploadFromUri:onSuccess"); // Get the public download URL mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl(); // [START_EXCLUDE] hideProgressDialog(); updateUI(mAuth.getCurrentUser()); // [END_EXCLUDE] } }).addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Upload failed Log.w(TAG, "uploadFromUri:onFailure", exception); mDownloadUrl = null; // [START_EXCLUDE] hideProgressDialog(); Toast.makeText(MainActivityStorage.this, "Error: upload failed", Toast.LENGTH_SHORT).show(); updateUI(mAuth.getCurrentUser()); // [END_EXCLUDE] } }); }
From source file:ai.api.sample.MainActivity.java
public synchronized void createCalendar(CalendarBuilderObject calendarObj) { Calendar startTimeMillis = Calendar.getInstance(); Calendar endTimeMillis = Calendar.getInstance(); startTimeMillis.set(calendarObj.getYear().intValue(), calendarObj.getMonth().intValue() - 1, calendarObj.getDay().intValue(), calendarObj.getHour().intValue(), calendarObj.getMinute().intValue()); endTimeMillis.set(calendarObj.getYear().intValue(), calendarObj.getMonth().intValue() - 1, calendarObj.getDay().intValue(), calendarObj.getHour().intValue(), calendarObj.getMinute().intValue() + 30); final ContentValues event = new ContentValues(); //event.put(CalendarContract.Reminders.DTSTART, startTimeMillis.getTimeInMillis()); event.put(CalendarContract.Events.CALENDAR_ID, 1); event.put(CalendarContract.Events.TITLE, calendarObj.getTaskTitle()); event.put(CalendarContract.Events.DESCRIPTION, calendarObj.getTaskTodo()); event.put(CalendarContract.Events.EVENT_LOCATION, ""); event.put(CalendarContract.Events.DTSTART, startTimeMillis.getTimeInMillis()); event.put(CalendarContract.Events.DTEND, endTimeMillis.getTimeInMillis()); event.put(CalendarContract.Events.ALL_DAY, 0); // 0 for false, 1 for true event.put(CalendarContract.Events.HAS_ALARM, 1); // 0 for false, 1 for true String timeZone = TimeZone.getDefault().getID(); event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone); Uri baseUri; baseUri = Uri.parse("content://com.android.calendar/events"); //getApplicationContext(); baseUri = getApplicationContext().getContentResolver().insert(baseUri, event); long eventID = Long.parseLong(baseUri.getLastPathSegment()); ContentValues reminders = new ContentValues(); reminders.put(CalendarContract.Reminders.EVENT_ID, eventID); reminders.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT); reminders.put(CalendarContract.Reminders.MINUTES, 10); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return;//from ww w. j av a 2s . c om } Uri uri2 = getApplicationContext().getContentResolver().insert(CalendarContract.Reminders.CONTENT_URI, reminders); }
From source file:net.peterkuterna.android.apps.devoxxsched.io.RemoteSessionsHandler.java
@Override public ArrayList<ContentProviderOperation> parse(ArrayList<JSONArray> entries, ContentResolver resolver) throws JSONException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); final HashSet<String> sessionIds = Sets.newHashSet(); final HashSet<String> trackIds = Sets.newHashSet(); final HashMap<String, HashSet<String>> sessionSpeakerIds = Maps.newHashMap(); final HashMap<String, HashSet<String>> sessionTagIds = Maps.newHashMap(); int nrEntries = 0; for (JSONArray sessions : entries) { Log.d(TAG, "Retrieved " + sessions.length() + " presentation entries."); nrEntries += sessions.length();/*from w w w .ja v a 2 s. c om*/ for (int i = 0; i < sessions.length(); i++) { JSONObject session = sessions.getJSONObject(i); String id = session.getString("id"); final String sessionId = sanitizeId(id); final Uri sessionUri = Sessions.buildSessionUri(sessionId); sessionIds.add(sessionId); int isStarred = isStarred(sessionUri, resolver); boolean sessionUpdated = false; boolean newSession = false; ContentProviderOperation.Builder builder; if (isRowExisting(sessionUri, SessionsQuery.PROJECTION, resolver)) { builder = ContentProviderOperation.newUpdate(sessionUri); builder.withValue(Sessions.NEW, false); sessionUpdated = isSessionUpdated(sessionUri, session, resolver); if (isRemoteSync()) { builder.withValue(Sessions.UPDATED, sessionUpdated); } } else { newSession = true; builder = ContentProviderOperation.newInsert(Sessions.CONTENT_URI); builder.withValue(Sessions.SESSION_ID, sessionId); if (!isLocalSync()) { builder.withValue(Sessions.NEW, true); } } final String type = session.getString("type"); if (newSession || sessionUpdated) { builder.withValue(Sessions.TITLE, session.getString("title")); builder.withValue(Sessions.EXPERIENCE, session.getString("experience")); builder.withValue(Sessions.TYPE, type); builder.withValue(Sessions.SUMMARY, session.getString("summary")); builder.withValue(Sessions.STARRED, isStarred); } builder.withValue(Sessions.TYPE_ID, getTypeId(type)); batch.add(builder.build()); if (session.has("track")) { final String trackName = session.getString("track"); final String trackId = Tracks.generateTrackId(trackName); final Uri trackUri = Tracks.buildTrackUri(trackId); if (!trackIds.contains(trackId)) { trackIds.add(trackId); ContentProviderOperation.Builder trackBuilder; if (isRowExisting(Tracks.buildTrackUri(trackId), TracksQuery.PROJECTION, resolver)) { trackBuilder = ContentProviderOperation.newUpdate(trackUri); } else { trackBuilder = ContentProviderOperation.newInsert(Tracks.CONTENT_URI); trackBuilder.withValue(Tracks.TRACK_ID, trackId); } trackBuilder.withValue(Tracks.TRACK_NAME, trackName); final int color = Color.parseColor(getTrackColor(trackId)); trackBuilder.withValue(Tracks.TRACK_COLOR, color); batch.add(trackBuilder.build()); } if (newSession || sessionUpdated) { builder.withValue(Sessions.TRACK_ID, trackId); } } if (session.has("speakers")) { final Uri speakerSessionsUri = Sessions.buildSpeakersDirUri(sessionId); final JSONArray speakers = session.getJSONArray("speakers"); final HashSet<String> speakerIds = Sets.newHashSet(); if (!isLocalSync()) { final boolean sessionSpeakersUpdated = isSessionSpeakersUpdated(speakerSessionsUri, speakers, resolver); if (sessionSpeakersUpdated) { Log.d(TAG, "Speakers of session with id " + sessionId + " was udpated."); batch.add(ContentProviderOperation.newUpdate(sessionUri) .withValue(Sessions.UPDATED, true).build()); } } for (int j = 0; j < speakers.length(); j++) { JSONObject speaker = speakers.getJSONObject(j); final Uri speakerUri = Uri.parse(speaker.getString("speakerUri")); final String speakerId = speakerUri.getLastPathSegment(); speakerIds.add(speakerId); batch.add(ContentProviderOperation.newInsert(speakerSessionsUri) .withValue(SessionsSpeakers.SPEAKER_ID, speakerId) .withValue(SessionsSpeakers.SESSION_ID, sessionId).build()); } sessionSpeakerIds.put(sessionId, speakerIds); } if (session.has("tags")) { final Uri tagSessionsUri = Sessions.buildTagsDirUri(sessionId); final JSONArray tags = session.getJSONArray("tags"); final HashSet<String> tagIds = Sets.newHashSet(); for (int j = 0; j < tags.length(); j++) { JSONObject tag = tags.getJSONObject(j); final String tagName = tag.getString("name").toLowerCase(); final String tagId = Tags.generateTagId(tagName); tagIds.add(tagId); batch.add(ContentProviderOperation.newInsert(Tags.CONTENT_URI).withValue(Tags.TAG_ID, tagId) .withValue(Tags.TAG_NAME, tagName).build()); batch.add(ContentProviderOperation.newInsert(SearchSuggest.CONTENT_URI) .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, tagName).build()); batch.add(ContentProviderOperation.newInsert(tagSessionsUri) .withValue(SessionsTags.TAG_ID, tagId).withValue(SessionsTags.SESSION_ID, sessionId) .build()); } sessionTagIds.put(sessionId, tagIds); } } } if (isRemoteSync() && nrEntries > 0) { for (Entry<String, HashSet<String>> entry : sessionSpeakerIds.entrySet()) { String sessionId = entry.getKey(); HashSet<String> speakerIds = entry.getValue(); final Uri speakerSessionsUri = Sessions.buildSpeakersDirUri(sessionId); HashSet<String> lostSpeakerIds = getLostIds(speakerIds, speakerSessionsUri, SpeakersQuery.PROJECTION, SpeakersQuery.SPEAKER_ID, resolver); for (String lostSpeakerId : lostSpeakerIds) { final Uri deleteUri = Sessions.buildSessionSpeakerUri(sessionId, lostSpeakerId); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); } } for (Entry<String, HashSet<String>> entry : sessionTagIds.entrySet()) { String sessionId = entry.getKey(); HashSet<String> tagIds = entry.getValue(); final Uri tagSessionsUri = Sessions.buildTagsDirUri(sessionId); HashSet<String> lostTagIds = getLostIds(tagIds, tagSessionsUri, TagsQuery.PROJECTION, TagsQuery.TAG_ID, resolver); for (String lostTagId : lostTagIds) { final Uri deleteUri = Sessions.buildSessionTagUri(sessionId, lostTagId); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); } } HashSet<String> lostTrackIds = getLostIds(trackIds, Tracks.CONTENT_URI, TracksQuery.PROJECTION, TracksQuery.TRACK_ID, resolver); for (String lostTrackId : lostTrackIds) { Uri deleteUri = Tracks.buildSessionsUri(lostTrackId); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); deleteUri = Tracks.buildTrackUri(lostTrackId); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); } HashSet<String> lostSessionIds = getLostIds(sessionIds, Sessions.CONTENT_URI, SessionsQuery.PROJECTION, SessionsQuery.SESSION_ID, resolver); for (String lostSessionId : lostSessionIds) { Uri deleteUri = Sessions.buildSpeakersDirUri(lostSessionId); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); deleteUri = Sessions.buildTagsDirUri(lostSessionId); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); deleteUri = Sessions.buildSessionUri(lostSessionId); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); } } return batch; }
From source file:org.cdmckay.android.provider.MediaWikiProvider.java
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { final List<String> segments = uri.getPathSegments(); switch (mUriMatcher.match(uri)) { case SEARCH://from ww w.ja va 2 s. c om return search(convertPathSegmentToApiUrl(segments.get(0)), uri.getLastPathSegment()); case PAGE_BY_TITLE: return getPageByTitle(convertPathSegmentToApiUrl(segments.get(0)), uri.getLastPathSegment()); case PAGE_BY_ID: return getPageById(convertPathSegmentToApiUrl(segments.get(0)), Long.valueOf(uri.getLastPathSegment())); case SECTIONS_BY_TITLE: return getSectionsByTitle(convertPathSegmentToApiUrl(segments.get(0)), segments.get(3)); default: throw new IllegalArgumentException("Unknown URI: " + uri); } }
From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferDBBase.java
/** * Deletes a record in the table./* ww w .j av a 2s.c o m*/ * * @param uri A Uri of the specific record. * @param selection The "where" clause of sql. * @param selectionArgs Strings in the "where" clause. * @return Number of rows deleted. */ public int delete(Uri uri, String selection, String[] selectionArgs) { final int uriType = uriMatcher.match(uri); int rowsDeleted = 0; ensureDatabaseOpen(); switch (uriType) { case TRANSFERS: rowsDeleted = database.delete(TransferTable.TABLE_TRANSFER, selection, selectionArgs); break; case TRANSFER_ID: final String id = uri.getLastPathSegment(); if (TextUtils.isEmpty(selection)) { rowsDeleted = database.delete(TransferTable.TABLE_TRANSFER, TransferTable.COLUMN_ID + "=" + id, null); } else { rowsDeleted = database.delete(TransferTable.TABLE_TRANSFER, TransferTable.COLUMN_ID + "=" + id + " and " + selection, selectionArgs); } break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } return rowsDeleted; }
From source file:com.google.samples.apps.iosched.service.SessionCalendarService.java
/** * Adds or removes a single session to/from the specified Google Calendar. *///from w w w . j ava 2s . c o m private ArrayList<ContentProviderOperation> processSessionCalendar(final ContentResolver resolver, final long calendarId, final boolean isAddEvent, final Uri sessionUri, final long sessionBlockStart, final long sessionBlockEnd, final String sessionTitle, final String sessionRoom) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Unable to find the Calendar associated with the user or permissions were revoked. if (calendarId == INVALID_CALENDAR_ID || !permissionsAlreadyGranted()) { return batch; } final String calendarEventTitle = makeCalendarEventTitle(sessionTitle); Cursor cursor; ContentValues values = new ContentValues(); // Add Calendar event. if (isAddEvent) { if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) { LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters."); return batch; } // Check if the calendar event exists first. If it does, we don't want to add a // duplicate one. //noinspection MissingPermission cursor = resolver.query(CalendarContract.Events.CONTENT_URI, // URI new String[] { CalendarContract.Events._ID }, // Projection CalendarContract.Events.CALENDAR_ID + "=? and " // Selection + CalendarContract.Events.TITLE + "=? and " + CalendarContract.Events.DTSTART + ">=? and " + CalendarContract.Events.DTEND + "<=?", new String[] { // Selection args Long.valueOf(calendarId).toString(), calendarEventTitle, Long.toString(Config.CONFERENCE_START_MILLIS), Long.toString(Config.CONFERENCE_END_MILLIS) }, null); long newEventId = -1; if (cursor != null && cursor.moveToFirst()) { // Calendar event already exists for this session. newEventId = cursor.getLong(0); cursor.close(); // Data fix (workaround): batch.add(ContentProviderOperation.newUpdate(CalendarContract.Events.CONTENT_URI) .withValue(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID()) .withSelection(CalendarContract.Events._ID + "=?", new String[] { Long.valueOf(newEventId).toString() }) .build()); // End data fix. } else { // Calendar event doesn't exist, create it. // NOTE: we can't use batch processing here because we need the result of // the insert. values.clear(); values.put(CalendarContract.Events.DTSTART, sessionBlockStart); values.put(CalendarContract.Events.DTEND, sessionBlockEnd); values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom); values.put(CalendarContract.Events.TITLE, calendarEventTitle); values.put(CalendarContract.Events.CALENDAR_ID, calendarId); values.put(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID()); @SuppressWarnings("MissingPermission") Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values); String eventId = eventUri.getLastPathSegment(); if (eventId == null) { return batch; // Should be empty at this point } newEventId = Long.valueOf(eventId); // Since we're adding session reminder to system notification, we're not creating // Calendar event reminders. If we were to create Calendar event reminders, this // is how we would do it. //values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId)); //values.put(CalendarContract.Reminders.MINUTES, 10); //values.put(CalendarContract.Reminders.METHOD, // CalendarContract.Reminders.METHOD_ALERT); // Or default? //cr.insert(CalendarContract.Reminders.CONTENT_URI, values); //values.clear(); } // Update the session in our own provider with the newly created calendar event ID. values.clear(); values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId); resolver.update(sessionUri, values, null, null); } else { // Remove Calendar event, if exists. // Get the event calendar id. cursor = resolver.query(sessionUri, new String[] { ScheduleContract.Sessions.SESSION_CAL_EVENT_ID }, null, null, null); long calendarEventId = -1; if (cursor != null && cursor.moveToFirst()) { calendarEventId = cursor.getLong(0); cursor.close(); } // Try to remove the Calendar Event based on key. If successful, move on; // otherwise, remove the event based on Event title. int affectedRows = 0; if (calendarEventId != -1) { //noinspection MissingPermission affectedRows = resolver.delete(CalendarContract.Events.CONTENT_URI, CalendarContract.Events._ID + "=?", new String[] { Long.valueOf(calendarEventId).toString() }); } if (affectedRows == 0) { //noinspection MissingPermission resolver.delete(CalendarContract.Events.CONTENT_URI, String.format("%s=? and %s=? and %s=? and %s=?", CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND), new String[] { Long.valueOf(calendarId).toString(), calendarEventTitle, Long.valueOf(sessionBlockStart).toString(), Long.valueOf(sessionBlockEnd).toString() }); } // Remove the session and calendar event association. values.clear(); values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null); resolver.update(sessionUri, values, null, null); } return batch; }