Example usage for android.content ContentUris withAppendedId

List of usage examples for android.content ContentUris withAppendedId

Introduction

In this page you can find the example usage for android.content ContentUris withAppendedId.

Prototype

public static Uri withAppendedId(Uri contentUri, long id) 

Source Link

Document

Appends the given ID to the end of the path.

Usage

From source file:at.bitfire.davdroid.resource.LocalCollection.java

/**
 * Finds a specific resource by ID. Only records matching sqlFilter are taken into account.
 * @param localID   ID of the resource/*from ww w  .  j  av a  2  s.  c  o m*/
 * @param populate   true: populates all data fields (for instance, contact or event details);
 *                false: only remote file name and ETag are populated
 * @return resource with either ID/remote file/name/ETag or all fields populated
 * @throws RecordNotFoundException when the resource couldn't be found
 * @throws LocalStorageException when the content provider couldn't be queried
 */
public T findById(long localID, boolean populate) throws LocalStorageException {
    try {
        @Cleanup
        Cursor cursor = providerClient.query(ContentUris.withAppendedId(entriesURI(), localID),
                new String[] { entryColumnRemoteName(), entryColumnETag() }, sqlFilter, null, null);
        if (cursor != null && cursor.moveToNext()) {
            T resource = newResource(localID, cursor.getString(0), cursor.getString(1));
            if (populate)
                populate(resource);
            return resource;
        } else
            throw new RecordNotFoundException();
    } catch (RemoteException ex) {
        throw new LocalStorageException(ex);
    }
}

From source file:com.jefftharris.passwdsafe.SyncProviderFilesFragment.java

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    Cursor cursor = (Cursor) getListAdapter().getItem(position);
    if ((cursor == null) || (itsListener == null)) {
        return;/*  w  w w  .  j a v  a  2  s  . c om*/
    }

    Uri uri = ContentUris.withAppendedId(itsFilesUri, id);
    PasswdSafeUtil.dbginfo(TAG, "Open provider uri %s", uri);
    itsListener.openFile(uri, cursor.getString(PasswdSafeContract.Files.PROJECTION_IDX_TITLE));
}

From source file:com.nbos.phonebook.sync.platform.ContactManager.java

/**
 * Deletes a contact from the platform contacts provider.
 * /*from  w w w .  ja v  a  2s  .  c  om*/
 * @param context the Authenticator Activity context
 * @param rawContactId the unique Id for this rawContact in contacts
 *        provider
 */
public static void deleteContact(Context context, long rawContactId, BatchOperation batchOperation) {
    batchOperation.add(ContactOperations
            .newDeleteCpo(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), true).build());
}

From source file:com.android.calendar.event.EditEventFragment.java

private void startQuery() {
    mUri = null;//from   ww w.  j  a  va2  s  .  c o  m
    mBegin = -1;
    mEnd = -1;
    if (mEvent != null) {
        if (mEvent.id != -1) {
            mModel.mId = mEvent.id;
            mUri = ContentUris.withAppendedId(Events.CONTENT_URI, mEvent.id);
        } else {
            // New event. All day?
            mModel.mAllDay = mEvent.extraLong == CalendarController.EXTRA_CREATE_ALL_DAY;
        }
        if (mEvent.startTime != null) {
            mBegin = mEvent.startTime.toMillis(true);
        }
        if (mEvent.endTime != null) {
            mEnd = mEvent.endTime.toMillis(true);
        }
        if (mEvent.calendarId != -1) {
            mCalendarId = mEvent.calendarId;
        }
    } else if (mEventBundle != null) {
        if (mEventBundle.id != -1) {
            mModel.mId = mEventBundle.id;
            mUri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventBundle.id);
        }
        mBegin = mEventBundle.start;
        mEnd = mEventBundle.end;
    }

    if (mReminders != null) {
        mModel.mReminders = mReminders;
    }

    if (mEventColorInitialized) {
        mModel.setEventColor(mEventColor);
    }

    if (mBegin <= 0) {
        // use a default value instead
        mBegin = mHelper.constructDefaultStartTime(System.currentTimeMillis());
    }
    if (mEnd < mBegin) {
        // use a default value instead
        mEnd = mHelper.constructDefaultEndTime(mBegin);
    }

    // Kick off the query for the event
    boolean newEvent = mUri == null;
    if (!newEvent) {
        mModel.mCalendarAccessLevel = Calendars.CAL_ACCESS_NONE;
        mOutstandingQueries = TOKEN_ALL;
        if (DEBUG) {
            Log.d(TAG, "startQuery: uri for event is " + mUri.toString());
        }
        mHandler.startQuery(TOKEN_EVENT, null, mUri, EditEventHelper.EVENT_PROJECTION, null /* selection */,
                null /* selection args */, null /* sort order */);
    } else {
        mOutstandingQueries = TOKEN_CALENDARS | TOKEN_COLORS;
        if (DEBUG) {
            Log.d(TAG, "startQuery: Editing a new event.");
        }
        mModel.mOriginalStart = mBegin;
        mModel.mOriginalEnd = mEnd;
        mModel.mStart = mBegin;
        mModel.mEnd = mEnd;
        mModel.mCalendarId = mCalendarId;
        mModel.mSelfAttendeeStatus = Attendees.ATTENDEE_STATUS_ACCEPTED;

        // Start a query in the background to read the list of calendars and colors
        mHandler.startQuery(TOKEN_CALENDARS, null, Calendars.CONTENT_URI, EditEventHelper.CALENDARS_PROJECTION,
                EditEventHelper.CALENDARS_WHERE_WRITEABLE_VISIBLE, null /* selection args */,
                null /* sort order */);

        mHandler.startQuery(TOKEN_COLORS, null, Colors.CONTENT_URI, EditEventHelper.COLORS_PROJECTION,
                Colors.COLOR_TYPE + "=" + Colors.TYPE_EVENT, null, null);

        mModification = Utils.MODIFY_ALL;
        mView.setModification(mModification);
    }
}

From source file:com.android.contacts.common.model.ContactLoaderTest.java

public void testLoadContactWithContactLookupAndIdUri() {
    // Use lookup-style Uris that also contain the Contact-ID
    final Uri baseUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, CONTACT_ID);
    final Uri lookupUri = ContentUris
            .withAppendedId(Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, LOOKUP_KEY), CONTACT_ID);
    final Uri entityUri = Uri.withAppendedPath(lookupUri, Contacts.Entity.CONTENT_DIRECTORY);

    ContactQueries queries = new ContactQueries();
    mContactsProvider.expectTypeQuery(lookupUri, Contacts.CONTENT_ITEM_TYPE);
    queries.fetchAllData(entityUri, CONTACT_ID, RAW_CONTACT_ID, DATA_ID, LOOKUP_KEY);

    Contact contact = assertLoadContact(lookupUri);

    assertEquals(CONTACT_ID, contact.getId());
    assertEquals(RAW_CONTACT_ID, contact.getNameRawContactId());
    assertEquals(DisplayNameSources.STRUCTURED_NAME, contact.getDisplayNameSource());
    assertEquals(LOOKUP_KEY, contact.getLookupKey());
    assertEquals(lookupUri, contact.getLookupUri());
    assertEquals(1, contact.getRawContacts().size());
    assertEquals(1, contact.getStatuses().size());
    mContactsProvider.verify();/*from   w  ww.  j a  va  2 s .c om*/
}

From source file:at.bitfire.davdroid.resource.LocalCalendar.java

@Override
public void updateMetaData(WebDavResource.Properties properties) throws LocalStorageException {
    ContentValues values = new ContentValues();

    final String displayName = properties.getDisplayName();
    if (displayName != null)
        values.put(Calendars.CALENDAR_DISPLAY_NAME, displayName);

    final Integer color = properties.getColor();
    if (color != null)
        values.put(Calendars.CALENDAR_COLOR, color);

    try {/*from   ww w.  j  a v a 2 s .c  om*/
        if (values.size() > 0)
            providerClient.update(ContentUris.withAppendedId(calendarsURI(), id), values, null, null);
    } catch (RemoteException e) {
        throw new LocalStorageException(e);
    }
}

From source file:org.thomnichols.android.gmarks.GmarksProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    // Validate the requested uri
    if (sUriMatcher.match(uri) != BOOKMARKS_URI) {
        throw new IllegalArgumentException("Unknown URI " + uri);
    }/*from   ww w . ja v a2  s .c o  m*/

    ContentValues values;
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    Long now = Long.valueOf(System.currentTimeMillis());

    // Make sure that the fields are all set
    if (values.containsKey(Bookmark.Columns.CREATED_DATE) == false) {
        values.put(Bookmark.Columns.CREATED_DATE, now);
    }

    if (values.containsKey(Bookmark.Columns.MODIFIED_DATE) == false) {
        values.put(Bookmark.Columns.MODIFIED_DATE, now);
    }

    if (values.containsKey(Bookmark.Columns.TITLE) == false) {
        Resources r = Resources.getSystem();
        values.put(Bookmark.Columns.TITLE, r.getString(android.R.string.untitled));
    }

    if (values.containsKey(Bookmark.Columns.DESCRIPTION) == false) {
        values.put(Bookmark.Columns.DESCRIPTION, "");
    }

    SQLiteDatabase db = dbHelper.getWritableDatabase();
    long rowId = db.insert(BOOKMARKS_TABLE_NAME, "", values);
    if (rowId > 0) {
        Uri noteUri = ContentUris.withAppendedId(Bookmark.CONTENT_URI, rowId);
        getContext().getContentResolver().notifyChange(noteUri, null);
        return noteUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:com.frostwire.android.gui.adapters.menu.FileListAdapter.java

private void populateViewThumbnail(View view, FileDescriptorItem item) {
    FileDescriptor fd = item.fd;/*w w w .  j  a  v a  2 s . com*/

    BrowseThumbnailImageButton fileThumbnail = findView(view, R.id.view_browse_peer_list_item_file_thumbnail);
    fileThumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);

    if (fileType == Constants.FILE_TYPE_APPLICATIONS) {
        Uri uri = Uri.withAppendedPath(ImageLoader.APPLICATION_THUMBNAILS_URI, fd.album);
        thumbnailLoader.load(uri, fileThumbnail, 96, 96);
    } else {
        if (in(fileType, Constants.FILE_TYPE_AUDIO, Constants.FILE_TYPE_VIDEOS,
                Constants.FILE_TYPE_RINGTONES)) {
            if (fd.equals(Engine.instance().getMediaPlayer().getCurrentFD())) {
                fileThumbnail.setOverlayState(MediaPlaybackOverlay.MediaPlaybackState.STOP);
            } else {
                fileThumbnail.setOverlayState(MediaPlaybackOverlay.MediaPlaybackState.PLAY);
            }
        }

        if (fd.fileType == Constants.FILE_TYPE_AUDIO) {
            Uri uri = ContentUris.withAppendedId(ImageLoader.ALBUM_THUMBNAILS_URI, fd.albumId);
            Uri uriRetry = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, fd.id);
            uriRetry = ImageLoader.getMetadataArtUri(uriRetry);
            thumbnailLoader.load(uri, uriRetry, fileThumbnail, 96, 96);
        } else if (fd.fileType == Constants.FILE_TYPE_VIDEOS) {
            Uri uri = ContentUris.withAppendedId(Video.Media.EXTERNAL_CONTENT_URI, fd.id);
            Uri uriRetry = ImageLoader.getMetadataArtUri(uri);
            thumbnailLoader.load(uri, uriRetry, fileThumbnail, 96, 96);
        } else if (fd.fileType == Constants.FILE_TYPE_PICTURES) {
            Uri uri = ContentUris.withAppendedId(Images.Media.EXTERNAL_CONTENT_URI, fd.id);
            thumbnailLoader.load(uri, fileThumbnail, 96, 96);
        }
    }

    TextView title = findView(view, R.id.view_browse_peer_list_item_file_title);
    title.setText(fd.title);

    if (fd.fileType == Constants.FILE_TYPE_AUDIO || fd.fileType == Constants.FILE_TYPE_APPLICATIONS) {
        TextView fileExtra = findView(view, R.id.view_browse_peer_list_item_extra_text);
        fileExtra.setText(fd.artist);
    } else {
        TextView fileExtra = findView(view, R.id.view_browse_peer_list_item_extra_text);
        fileExtra.setText(R.string.empty_string);
    }

    TextView fileSize = findView(view, R.id.view_browse_peer_list_item_file_size);
    fileSize.setText(UIUtils.getBytesInHuman(fd.fileSize));

    fileThumbnail.setTag(fd);
    fileThumbnail.setOnClickListener(downloadButtonClickListener);

    populateSDState(view, item);
}

From source file:com.android.email_ee.LegacyConversions.java

/**
 * Add a single attachment part to the message
 *
 * This will skip adding attachments if they are already found in the attachments table.
 * The heuristic for this will fail (false-positive) if two identical attachments are
 * included in a single POP3 message./*from  w w w .  j  a va  2 s  .c o  m*/
 * TODO: Fix that, by (elsewhere) simulating an mLocation value based on the attachments
 * position within the list of multipart/mixed elements.  This would make every POP3 attachment
 * unique, and might also simplify the code (since we could just look at the positions, and
 * ignore the filename, etc.)
 *
 * TODO: Take a closer look at encoding and deal with it if necessary.
 *
 * @param context a context for file operations
 * @param localMessage the attachments will be built against this message
 * @param part a single attachment part from POP or IMAP
 * @throws IOException
 */
public static void addOneAttachment(Context context, EmailContent.Message localMessage, Part part)
        throws MessagingException, IOException {

    Attachment localAttachment = new Attachment();

    // Transfer fields from mime format to provider format
    String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
    String name = MimeUtility.getHeaderParameter(contentType, "name");
    if (name == null) {
        String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition());
        name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
    }

    // Incoming attachment: Try to pull size from disposition (if not downloaded yet)
    long size = 0;
    String disposition = part.getDisposition();
    if (disposition != null) {
        String s = MimeUtility.getHeaderParameter(disposition, "size");
        if (s != null) {
            size = Long.parseLong(s);
        }
    }

    // Get partId for unloaded IMAP attachments (if any)
    // This is only provided (and used) when we have structure but not the actual attachment
    String[] partIds = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA);
    String partId = partIds != null ? partIds[0] : null;

    // Run the mime type through inferMimeType in case we have something generic and can do
    // better using the filename extension
    String mimeType = AttachmentUtilities.inferMimeType(name, part.getMimeType());
    localAttachment.mMimeType = mimeType;
    localAttachment.mFileName = name;
    localAttachment.mSize = size; // May be reset below if file handled
    localAttachment.mContentId = part.getContentId();
    localAttachment.setContentUri(null); // Will be rewritten by saveAttachmentBody
    localAttachment.mMessageKey = localMessage.mId;
    localAttachment.mLocation = partId;
    localAttachment.mEncoding = "B"; // TODO - convert other known encodings
    localAttachment.mAccountKey = localMessage.mAccountKey;

    if (DEBUG_ATTACHMENTS) {
        LogUtils.d(Logging.LOG_TAG, "Add attachment " + localAttachment);
    }

    // To prevent duplication - do we already have a matching attachment?
    // The fields we'll check for equality are:
    //  mFileName, mMimeType, mContentId, mMessageKey, mLocation
    // NOTE:  This will false-positive if you attach the exact same file, twice, to a POP3
    // message.  We can live with that - you'll get one of the copies.
    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId);
    Cursor cursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null, null, null);
    boolean attachmentFoundInDb = false;
    try {
        while (cursor.moveToNext()) {
            Attachment dbAttachment = new Attachment();
            dbAttachment.restore(cursor);
            // We test each of the fields here (instead of in SQL) because they may be
            // null, or may be strings.
            if (stringNotEqual(dbAttachment.mFileName, localAttachment.mFileName))
                continue;
            if (stringNotEqual(dbAttachment.mMimeType, localAttachment.mMimeType))
                continue;
            if (stringNotEqual(dbAttachment.mContentId, localAttachment.mContentId))
                continue;
            if (stringNotEqual(dbAttachment.mLocation, localAttachment.mLocation))
                continue;
            // We found a match, so use the existing attachment id, and stop looking/looping
            attachmentFoundInDb = true;
            localAttachment.mId = dbAttachment.mId;
            if (DEBUG_ATTACHMENTS) {
                LogUtils.d(Logging.LOG_TAG, "Skipped, found db attachment " + dbAttachment);
            }
            break;
        }
    } finally {
        cursor.close();
    }

    // Save the attachment (so far) in order to obtain an id
    if (!attachmentFoundInDb) {
        localAttachment.save(context);
    }

    // If an attachment body was actually provided, we need to write the file now
    saveAttachmentBody(context, part, localAttachment, localMessage.mAccountKey);

    if (localMessage.mAttachments == null) {
        localMessage.mAttachments = new ArrayList<Attachment>();
    }
    localMessage.mAttachments.add(localAttachment);
    localMessage.mFlagAttachment = true;
}