List of usage examples for android.content ContentUris parseId
public static long parseId(Uri contentUri)
From source file:org.gege.caldavsyncadapter.syncadapter.SyncAdapter.java
/** * checks the android events for the dirty flag. * the flag is set by android when the event has been changed. * the dirty flag is removed when an android event has been updated from calendar event * @param provider//from www .j av a2 s . c o m * @param account * @param calendarUri * @param facade * @param caldavCalendarUri * @param stats * @param notifyList * @return count of dirty events */ private int checkDirtyAndroidEvents(ContentProviderClient provider, Account account, Uri calendarUri, CaldavFacade facade, URI caldavCalendarUri, SyncStats stats, ArrayList<Uri> notifyList) { Cursor curEvent = null; Cursor curAttendee = null; Cursor curReminder = null; Long EventID; Long CalendarID; AndroidEvent androidEvent = null; int rowDirty = 0; int rowInsert = 0; int rowUpdate = 0; int rowDelete = 0; try { CalendarID = ContentUris.parseId(calendarUri); String selection = "(" + Events.DIRTY + " = ?) AND (" + Events.CALENDAR_ID + " = ?)"; String[] selectionArgs = new String[] { "1", CalendarID.toString() }; curEvent = provider.query(Events.CONTENT_URI, null, selection, selectionArgs, null); while (curEvent.moveToNext()) { EventID = curEvent.getLong(curEvent.getColumnIndex(Events._ID)); Uri returnedUri = ContentUris.withAppendedId(Events.CONTENT_URI, EventID); androidEvent = new AndroidEvent(account, provider, returnedUri, calendarUri); androidEvent.readContentValues(curEvent); selection = "(" + Attendees.EVENT_ID + " = ?)"; selectionArgs = new String[] { String.valueOf(EventID) }; curAttendee = provider.query(Attendees.CONTENT_URI, null, selection, selectionArgs, null); selection = "(" + Reminders.EVENT_ID + " = ?)"; selectionArgs = new String[] { String.valueOf(EventID) }; curReminder = provider.query(Reminders.CONTENT_URI, null, selection, selectionArgs, null); androidEvent.readAttendees(curAttendee); androidEvent.readReminder(curReminder); curAttendee.close(); curReminder.close(); String SyncID = androidEvent.ContentValues.getAsString(Events._SYNC_ID); boolean Deleted = false; int intDeleted = 0; intDeleted = curEvent.getInt(curEvent.getColumnIndex(Events.DELETED)); Deleted = (intDeleted == 1); if (SyncID == null) { // new Android event String newGUID = java.util.UUID.randomUUID().toString() + "-caldavsyncadapter"; String calendarPath = caldavCalendarUri.getPath(); if (!calendarPath.endsWith("/")) calendarPath += "/"; SyncID = calendarPath + newGUID + ".ics"; androidEvent.createIcs(newGUID); if (facade.createEvent(URI.create(SyncID), androidEvent.getIcsEvent().toString())) { //HINT: bugfix for google calendar if (SyncID.contains("@")) SyncID = SyncID.replace("@", "%40"); ContentValues values = new ContentValues(); values.put(Events._SYNC_ID, SyncID); //google doesn't send the etag after creation //HINT: my SabreDAV send always the same etag after putting a new event //String LastETag = facade.getLastETag(); //if (!LastETag.equals("")) { // values.put(Event.ETAG, LastETag); //} else { //so get the etag with a new REPORT CalendarEvent calendarEvent = new CalendarEvent(account, provider); calendarEvent.calendarURL = caldavCalendarUri.toURL(); URI SyncURI = new URI(SyncID); calendarEvent.setUri(SyncURI); CaldavFacade.getEvent(calendarEvent); values.put(Event.ETAG, calendarEvent.getETag()); //} values.put(Event.UID, newGUID); values.put(Events.DIRTY, 0); values.put(Event.RAWDATA, androidEvent.getIcsEvent().toString()); int rowCount = provider.update( asSyncAdapter(androidEvent.getUri(), account.name, account.type), values, null, null); if (rowCount == 1) { rowInsert += 1; notifyList.add(androidEvent.getUri()); } } } else if (Deleted) { // deleted Android event if (facade.deleteEvent(URI.create(SyncID), androidEvent.getETag())) { String mSelectionClause = "(" + Events._ID + "= ?)"; String[] mSelectionArgs = { String.valueOf(EventID) }; int countDeleted = provider.delete( asSyncAdapter(Events.CONTENT_URI, account.name, account.type), mSelectionClause, mSelectionArgs); if (countDeleted == 1) { rowDelete += 1; notifyList.add(androidEvent.getUri()); } } } else { //update the android event to the server String uid = androidEvent.getUID(); if ((uid == null) || (uid.equals(""))) { //COMPAT: this is needed because in the past, the UID was not stored in the android event CalendarEvent calendarEvent = new CalendarEvent(account, provider); URI syncURI = new URI(SyncID); calendarEvent.setUri(syncURI); calendarEvent.calendarURL = caldavCalendarUri.toURL(); if (calendarEvent.fetchBody()) { calendarEvent.readContentValues(); uid = calendarEvent.getUID(); } } if (uid != null) { androidEvent.createIcs(uid); if (facade.updateEvent(URI.create(SyncID), androidEvent.getIcsEvent().toString(), androidEvent.getETag())) { selection = "(" + Events._ID + "= ?)"; selectionArgs = new String[] { EventID.toString() }; androidEvent.ContentValues.put(Events.DIRTY, 0); //google doesn't send the etag after update String LastETag = facade.getLastETag(); if (!LastETag.equals("")) { androidEvent.ContentValues.put(Event.ETAG, LastETag); } else { //so get the etag with a new REPORT CalendarEvent calendarEvent = new CalendarEvent(account, provider); calendarEvent.calendarURL = caldavCalendarUri.toURL(); URI SyncURI = new URI(SyncID); calendarEvent.setUri(SyncURI); CaldavFacade.getEvent(calendarEvent); androidEvent.ContentValues.put(Event.ETAG, calendarEvent.getETag()); } androidEvent.ContentValues.put(Event.RAWDATA, androidEvent.getIcsEvent().toString()); int RowCount = provider.update( asSyncAdapter(androidEvent.getUri(), account.name, account.type), androidEvent.ContentValues, null, null); if (RowCount == 1) { rowUpdate += 1; notifyList.add(androidEvent.getUri()); } } else { rowDirty += 1; } } else { rowDirty += 1; } } } curEvent.close(); /*if ((rowInsert > 0) || (rowUpdate > 0) || (rowDelete > 0) || (rowDirty > 0)) { Log.i(TAG,"Android Rows inserted: " + String.valueOf(rowInsert)); Log.i(TAG,"Android Rows updated: " + String.valueOf(rowUpdate)); Log.i(TAG,"Android Rows deleted: " + String.valueOf(rowDelete)); Log.i(TAG,"Android Rows dirty: " + String.valueOf(rowDirty)); }*/ stats.numInserts += rowInsert; stats.numUpdates += rowUpdate; stats.numDeletes += rowDelete; stats.numSkippedEntries += rowDirty; stats.numEntries += rowInsert + rowUpdate + rowDelete; } catch (RemoteException e) { e.printStackTrace(); } catch (URISyntaxException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (IOException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (CaldavProtocolException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (ParserException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } return rowDirty; }
From source file:org.totschnig.myexpenses.MyApplication.java
private boolean insertEventAndUpdatePlan(ContentValues eventValues, long templateId) { Uri uri = getContentResolver().insert(Events.CONTENT_URI, eventValues); long planId = ContentUris.parseId(uri); Log.i(TAG, "event copied with new id: " + planId); ContentValues planValues = new ContentValues(); planValues.put(DatabaseConstants.KEY_PLANID, planId); int updated = getContentResolver().update(ContentUris.withAppendedId(Template.CONTENT_URI, templateId), planValues, null, null);//w w w .jav a 2s.co m return updated > 0; }
From source file:edu.cens.loci.ui.PlaceViewActivity.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult:" + String.format(" requestCode=%d resultCode=%d ", requestCode, resultCode)); switch (requestCode) { case SUBACTIVITY_ADD_PLACE: if (resultCode == RESULT_OK) { long placeId = ContentUris.parseId(data.getData()); if (mPlace.state == Places.STATE_SUGGESTED) { if (placeId != mPlaceId) { // A suggested place has been merged to an existing place // update all visit's placeId's here LociDbUtils dbUtils = new LociDbUtils(this); dbUtils.updateVisitPlaceId(mPlaceId, placeId); mPlaceId = placeId;//w w w. j av a2s . c o m } } setResult(RESULT_OK, data); } break; case SUBACTIVITY_VIEW_PLACE: if (resultCode == RESULT_OK) { } } }
From source file:org.mythtv.service.content.v25.LiveStreamHelperV25.java
private boolean save(final Context context, final LocationProfile locationProfile, LiveStreamInfo liveStreamInfo, int channelId, DateTime startTime) { Log.d(TAG, "save : enter"); if (null == context) throw new RuntimeException("LiveStreamHelperV25 is not initialized"); DateTime lastModified = new DateTime(DateTimeZone.UTC); boolean saved = false; ContentValues values = convertLiveStreamInfoToContentValues(locationProfile, liveStreamInfo, lastModified, channelId, startTime);/*w w w.ja v a2 s. c o m*/ String[] projection = new String[] { LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID }; String selection = LiveStreamConstants.FIELD_ID + " = ?"; String[] selectionArgs = new String[] { String.valueOf(liveStreamInfo.getId()) }; selection = appendLocationHostname(context, locationProfile, selection, LiveStreamConstants.TABLE_NAME); Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection, selection, selectionArgs, null); if (cursor.moveToFirst()) { Log.v(TAG, "save : updating existing liveStream info"); long id = cursor.getLong( cursor.getColumnIndexOrThrow(LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID)); int updated = context.getContentResolver() .update(ContentUris.withAppendedId(LiveStreamConstants.CONTENT_URI, id), values, null, null); if (updated == 1) { saved = true; } } else { Log.v(TAG, "save : inserting new liveStream info"); Uri url = context.getContentResolver().insert(LiveStreamConstants.CONTENT_URI, values); if (ContentUris.parseId(url) > 0) { saved = true; } } cursor.close(); Log.d(TAG, "save : exit"); return saved; }
From source file:org.mythtv.service.content.v26.LiveStreamHelperV26.java
private boolean save(final Context context, final LocationProfile locationProfile, LiveStreamInfo liveStreamInfo, int channelId, DateTime startTime) { Log.d(TAG, "save : enter"); if (null == context) throw new RuntimeException("LiveStreamHelperV26 is not initialized"); DateTime lastModified = new DateTime(DateTimeZone.UTC); boolean saved = false; ContentValues values = convertLiveStreamInfoToContentValues(locationProfile, liveStreamInfo, lastModified, channelId, startTime);//from ww w .j a v a 2s. c o m String[] projection = new String[] { LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID }; String selection = LiveStreamConstants.FIELD_ID + " = ?"; String[] selectionArgs = new String[] { String.valueOf(liveStreamInfo.getId()) }; selection = appendLocationHostname(context, locationProfile, selection, LiveStreamConstants.TABLE_NAME); Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection, selection, selectionArgs, null); if (cursor.moveToFirst()) { Log.v(TAG, "save : updating existing liveStream info"); long id = cursor.getLong( cursor.getColumnIndexOrThrow(LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID)); int updated = context.getContentResolver() .update(ContentUris.withAppendedId(LiveStreamConstants.CONTENT_URI, id), values, null, null); if (updated == 1) { saved = true; } } else { Log.v(TAG, "save : inserting new liveStream info"); Uri url = context.getContentResolver().insert(LiveStreamConstants.CONTENT_URI, values); if (ContentUris.parseId(url) > 0) { saved = true; } } cursor.close(); Log.d(TAG, "save : exit"); return saved; }
From source file:org.mythtv.service.content.v27.LiveStreamHelperV27.java
private boolean save(final Context context, final LocationProfile locationProfile, LiveStreamInfo liveStreamInfo, int channelId, DateTime startTime) { Log.d(TAG, "save : enter"); if (null == context) throw new RuntimeException("LiveStreamHelperV27 is not initialized"); DateTime lastModified = new DateTime(DateTimeZone.UTC); boolean saved = false; ContentValues values = convertLiveStreamInfoToContentValues(locationProfile, liveStreamInfo, lastModified, channelId, startTime);/*from w w w .j a v a 2 s .com*/ String[] projection = new String[] { LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID }; String selection = LiveStreamConstants.FIELD_ID + " = ?"; String[] selectionArgs = new String[] { String.valueOf(liveStreamInfo.getId()) }; selection = appendLocationHostname(context, locationProfile, selection, LiveStreamConstants.TABLE_NAME); Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection, selection, selectionArgs, null); if (cursor.moveToFirst()) { Log.v(TAG, "save : updating existing liveStream info"); long id = cursor.getLong( cursor.getColumnIndexOrThrow(LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID)); int updated = context.getContentResolver() .update(ContentUris.withAppendedId(LiveStreamConstants.CONTENT_URI, id), values, null, null); if (updated == 1) { saved = true; } } else { Log.v(TAG, "save : inserting new liveStream info"); Uri url = context.getContentResolver().insert(LiveStreamConstants.CONTENT_URI, values); if (ContentUris.parseId(url) > 0) { saved = true; } } cursor.close(); Log.d(TAG, "save : exit"); return saved; }
From source file:org.dmfs.webcal.fragments.CalendarItemFragment.java
private void setCalendarSynced(final boolean status) { final Activity activity = getActivity(); if (mSynced != status) { new ProtectedBackgroundJob<Void, Uri>(activity) { @Override//from ww w .jav a2 s.c om protected void doPostExecute(Uri result) { mSubscriptionUri = result; } @Override protected Uri doInBackground(Void... params) { mSynced = status; if (status) { if (mSubscriptionUri != null) { // calendar already exists, we just have to enable sync ContentValues values = new ContentValues(); values.put(SubscribedCalendars.SYNC_ENABLED, 1); SubscribedCalendars.updateCalendar(activity, mSubscriptionUri, values); return mSubscriptionUri; } else { return SubscribedCalendars.addCalendar(activity, ContentUris.parseId(mContentUri), mCalendarName, (int) (Math.random() * 0x1000000) + 0xff000000); } } else { if (mSubscriptionUri != null) { SubscribedCalendars.disableCalendar(activity, mSubscriptionUri); } return null; } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }
From source file:edu.mit.mobile.android.locast.data.MediaSync.java
private String generateThumbnail(Uri castMedia, String mimeType, String locMedia) throws ThumbnailException { final long locId = ContentUris.parseId(Uri.parse(locMedia)); Bitmap thumb;// w ww. j a v a2s. c om if (mimeType.startsWith("image/")) { thumb = Images.Thumbnails.getThumbnail(getContentResolver(), locId, Images.Thumbnails.MINI_KIND, null); } else if (mimeType.startsWith("video/")) { thumb = Video.Thumbnails.getThumbnail(getContentResolver(), locId, Video.Thumbnails.MINI_KIND, null); } else { throw new IllegalArgumentException( "cannot generate thumbnail for item with MIME type: '" + mimeType + "'"); } if (thumb == null) { throw new ThumbnailException("Android thumbnail generator returned null"); } try { final File outFile = new File(getCacheDir(), "thumb" + sha1Sum(locMedia) + ".jpg"); // final File outFile = File.createTempFile("thumb", ".jpg", // getCacheDir()); if (!outFile.exists()) { if (!outFile.createNewFile()) { throw new IOException("cannot create new file"); } if (DEBUG) { Log.d(TAG, "attempting to save thumb in " + outFile); } final FileOutputStream fos = new FileOutputStream(outFile); thumb.compress(CompressFormat.JPEG, 75, fos); thumb.recycle(); fos.close(); if (DEBUG) { Log.d(TAG, "generated thumbnail for " + locMedia + " and saved it in " + outFile.getAbsolutePath()); } } return Uri.fromFile(outFile).toString(); } catch (final IOException ioe) { final ThumbnailException te = new ThumbnailException(); te.initCause(ioe); throw te; } }
From source file:com.fututel.db.DBProvider.java
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Constructs a new query builder and sets its table name SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String finalSortOrder = sortOrder; String[] finalSelectionArgs = selectionArgs; String finalGrouping = null;/*from w ww. jav a2s. c o m*/ String finalHaving = null; int type = URI_MATCHER.match(uri); Uri regUri = uri; int remoteUid = Binder.getCallingUid(); int selfUid = android.os.Process.myUid(); if (remoteUid != selfUid) { if (type == ACCOUNTS || type == ACCOUNTS_ID) { for (String proj : projection) { if (proj.toLowerCase().contains(SipProfile.FIELD_DATA) || proj.toLowerCase().contains("*")) { throw new SecurityException("Password not readable from external apps"); } } } } Cursor c; long id; switch (type) { case ACCOUNTS: qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME); if (sortOrder == null) { finalSortOrder = SipProfile.FIELD_PRIORITY + " ASC"; } break; case ACCOUNTS_ID: qb.setTables(SipProfile.ACCOUNTS_TABLE_NAME); qb.appendWhere(SipProfile.FIELD_ID + "=?"); finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs, new String[] { uri.getLastPathSegment() }); break; case CALLLOGS: qb.setTables(SipManager.CALLLOGS_TABLE_NAME); if (sortOrder == null) { finalSortOrder = CallLog.Calls.DATE + " DESC"; } break; case CALLLOGS_ID: qb.setTables(SipManager.CALLLOGS_TABLE_NAME); qb.appendWhere(CallLog.Calls._ID + "=?"); finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs, new String[] { uri.getLastPathSegment() }); break; case FILTERS: qb.setTables(SipManager.FILTERS_TABLE_NAME); if (sortOrder == null) { finalSortOrder = Filter.DEFAULT_ORDER; } break; case FILTERS_ID: qb.setTables(SipManager.FILTERS_TABLE_NAME); qb.appendWhere(Filter._ID + "=?"); finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs, new String[] { uri.getLastPathSegment() }); break; case MESSAGES: qb.setTables(SipMessage.MESSAGES_TABLE_NAME); if (sortOrder == null) { finalSortOrder = SipMessage.FIELD_DATE + " DESC"; } break; case MESSAGES_ID: qb.setTables(SipMessage.MESSAGES_TABLE_NAME); qb.appendWhere(SipMessage.FIELD_ID + "=?"); finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs, new String[] { uri.getLastPathSegment() }); break; case THREADS: qb.setTables(SipMessage.MESSAGES_TABLE_NAME); if (sortOrder == null) { finalSortOrder = SipMessage.FIELD_DATE + " DESC"; } projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_FROM_FULL, SipMessage.FIELD_TO, "CASE " + "WHEN " + SipMessage.FIELD_FROM + "='SELF' THEN " + SipMessage.FIELD_TO + " WHEN " + SipMessage.FIELD_FROM + "!='SELF' THEN " + SipMessage.FIELD_FROM + " END AS message_ordering", SipMessage.FIELD_BODY, "MAX(" + SipMessage.FIELD_DATE + ") AS " + SipMessage.FIELD_DATE, "MIN(" + SipMessage.FIELD_READ + ") AS " + SipMessage.FIELD_READ, //SipMessage.FIELD_READ, "COUNT(" + SipMessage.FIELD_DATE + ") AS counter" }; //qb.appendWhere(SipMessage.FIELD_TYPE + " in (" + SipMessage.MESSAGE_TYPE_INBOX // + "," + SipMessage.MESSAGE_TYPE_SENT + ")"); finalGrouping = "message_ordering"; regUri = SipMessage.MESSAGE_URI; break; case THREADS_ID: qb.setTables(SipMessage.MESSAGES_TABLE_NAME); if (sortOrder == null) { finalSortOrder = SipMessage.FIELD_DATE + " DESC"; } projection = new String[] { "ROWID AS _id", SipMessage.FIELD_FROM, SipMessage.FIELD_TO, SipMessage.FIELD_BODY, SipMessage.FIELD_DATE, SipMessage.FIELD_MIME_TYPE, SipMessage.FIELD_TYPE, SipMessage.FIELD_STATUS, SipMessage.FIELD_FROM_FULL }; qb.appendWhere(MESSAGES_THREAD_SELECTION); String from = uri.getLastPathSegment(); finalSelectionArgs = DatabaseUtilsCompat.appendSelectionArgs(selectionArgs, new String[] { from, from }); regUri = SipMessage.MESSAGE_URI; break; case ACCOUNTS_STATUS: synchronized (profilesStatus) { ContentValues[] cvs = new ContentValues[profilesStatus.size()]; int i = 0; for (ContentValues ps : profilesStatus.values()) { cvs[i] = ps; i++; } c = getCursor(cvs); } if (c != null) { c.setNotificationUri(getContext().getContentResolver(), uri); } return c; case ACCOUNTS_STATUS_ID: id = ContentUris.parseId(uri); synchronized (profilesStatus) { ContentValues cv = profilesStatus.get(id); if (cv == null) { return null; } c = getCursor(new ContentValues[] { cv }); } c.setNotificationUri(getContext().getContentResolver(), uri); return c; default: throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri); } SQLiteDatabase db = mOpenHelper.getReadableDatabase(); c = qb.query(db, projection, selection, finalSelectionArgs, finalGrouping, finalHaving, finalSortOrder); c.setNotificationUri(getContext().getContentResolver(), regUri); return c; }
From source file:cz.maresmar.sfm.view.portal.PortalDetailFragment.java
@UiThread @Override/*from w ww . j av a 2s .c o m*/ public boolean hasValidData() { boolean isValid = true; // Portal name test if (mNameText.getText().length() == 0) { mNameText.setError(getString(R.string.portal_name_empty_error)); isValid = false; } else { // Test if portal name is unique long currentId; if (mPortalUri != null) { currentId = ContentUris.parseId(mPortalUri); } else { currentId = -1; } String portalName = mNameText.getText().toString(); try (Cursor cursor = getContext().getContentResolver().query(ProviderContract.Portal.getUri(), new String[] { ProviderContract.Portal.PORTAL_ID }, ProviderContract.Portal.NAME + " == ? AND " + ProviderContract.Portal.PORTAL_ID + " != ?", new String[] { portalName, "" + currentId }, null)) { if (cursor.getCount() == 0) { mNameText.setError(null); } else { mNameText.setError(getString(R.string.portal_name_used_error)); isValid = false; } } } if (!hasValidExtraData()) { isValid = false; } if (!isValid) { //noinspection ConstantConditions Snackbar.make(getView(), R.string.extra_invalid_input_error, Snackbar.LENGTH_LONG) .setAction(android.R.string.ok, view -> { // Only dismiss message }).show(); } return isValid; }