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:com.grokkingandroid.sampleapp.samples.data.contentprovider.lentitems.LentItemDisplayFragment.java

@Override
public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) {
    Uri loaderUri = ContentUris.withAppendedId(ItemEntities.CONTENT_URI, mItemId);
    return new CursorLoader(getActivity(), loaderUri, ItemEntities.PROJECTION_ALL, null, null, null);
    // // to compare:
    // // you would use a CP directly like this:
    ///*from ww w.  ja  v a2 s .co  m*/
    // ContentResolver resolver =
    // getActivity().getContentResolver();
    // resolver.query(
    //     loaderUri,                      // the URI to query
    //     ItemsEntities.PROJECTION_ALL,   // the projection to use
    //     null,                           // the where clause without the WHERE keyword
    //     null,                           // any wildcard substitutions
    //     null);                          // the sort order without the SORT BY keyword
}

From source file:com.android.exchange.eas.EasSync.java

/**
 * @return Number of messages successfully synced, or a negative response code from
 *         {@link EasOperation} if we encountered any errors.
 */// ww  w .j  av  a 2  s .  c o  m
public final int upsync() {
    final List<MessageStateChange> changes = MessageStateChange.getChanges(mContext, getAccountId(),
            getProtocolVersion() < Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE);
    if (changes == null) {
        return 0;
    }
    final LongSparseArray<List<MessageStateChange>> allData = MessageStateChange.convertToChangesMap(changes);
    if (allData == null) {
        return 0;
    }

    final long[][] messageIds = new long[2][changes.size()];
    final int[] counts = new int[2];
    int result = 0;

    for (int i = 0; i < allData.size(); ++i) {
        mMailboxId = allData.keyAt(i);
        mStateChanges = allData.valueAt(i);
        boolean retryMailbox = true;
        // If we've already encountered a fatal error, don't even try to upsync subsequent
        // mailboxes.
        if (result >= 0) {
            final Cursor mailboxCursor = mContext.getContentResolver().query(
                    ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailboxId),
                    Mailbox.ProjectionSyncData.PROJECTION, null, null, null);
            if (mailboxCursor != null) {
                try {
                    if (mailboxCursor.moveToFirst()) {
                        mMailboxServerId = mailboxCursor.getString(Mailbox.ProjectionSyncData.COLUMN_SERVER_ID);
                        mMailboxSyncKey = mailboxCursor.getString(Mailbox.ProjectionSyncData.COLUMN_SYNC_KEY);
                        if (TextUtils.isEmpty(mMailboxSyncKey) || mMailboxSyncKey.equals("0")) {
                            // For some reason we can get here without a valid mailbox sync key
                            // b/10797675
                            // TODO: figure out why and clean this up
                            LogUtils.d(LOG_TAG, "Tried to sync mailbox %d with invalid mailbox sync key",
                                    mMailboxId);
                        } else {
                            result = performOperation();
                            if (result >= 0) {
                                // Our request gave us back a legitimate answer; this is the
                                // only case in which we don't retry this mailbox.
                                retryMailbox = false;
                                if (result == RESULT_OK) {
                                    handleMessageUpdateStatus(mMessageUpdateStatus, messageIds, counts);
                                } else if (result == RESULT_NO_MAILBOX) {
                                    // A retry here is pointless -- the message's mailbox (and
                                    // therefore the message) is gone, so mark as success so
                                    // that these entries get wiped from the change list.
                                    for (final MessageStateChange msc : mStateChanges) {
                                        messageIds[0][counts[0]] = msc.getMessageId();
                                        ++counts[0];
                                    }
                                } else {
                                    LogUtils.wtf(LOG_TAG, "Unrecognized result code: %d", result);
                                }
                            }
                        }
                    }
                } finally {
                    mailboxCursor.close();
                }
            }
        }
        if (retryMailbox) {
            for (final MessageStateChange msc : mStateChanges) {
                messageIds[1][counts[1]] = msc.getMessageId();
                ++counts[1];
            }
        }
    }

    final ContentResolver cr = mContext.getContentResolver();
    MessageStateChange.upsyncSuccessful(cr, messageIds[0], counts[0]);
    MessageStateChange.upsyncRetry(cr, messageIds[1], counts[1]);

    if (result < 0) {
        return result;
    }
    return counts[0];
}

From source file:org.c99.SyncProviderDemo.ContactsSyncAdapterService.java

private static void updateContactStatus(ArrayList<ContentProviderOperation> operationList, long rawContactId,
        String status) {/*from www  .  j  a va2  s  . c om*/
    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);
    try {
        while (c.moveToNext()) {
            if (!c.isNull(1)) {
                String mimeType = c.getString(2);

                if (mimeType.equals("vnd.android.cursor.item/vnd.org.c99.SyncProviderDemo.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.c99.SyncProviderDemo");
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_LABEL, R.string.app_name);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_ICON, R.drawable.logo);
                    builder.withValue(ContactsContract.StatusUpdates.STATUS_TIMESTAMP,
                            System.currentTimeMillis());
                    operationList.add(builder.build());

                    //Only change the text of our custom entry to the status message pre-Honeycomb, as the newer contacts app shows
                    //statuses elsewhere
                    if (Integer.decode(Build.VERSION.SDK) < 11) {
                        builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
                        builder.withSelection(BaseColumns._ID + " = '" + c.getLong(1) + "'", null);
                        builder.withValue(ContactsContract.Data.DATA3, status);
                        operationList.add(builder.build());
                    }
                }
            }
        }
    } finally {
        c.close();
    }
}

From source file:com.android.contacts.common.vcard.NotificationImportExportListener.java

@Override
public void onImportFinished(ImportRequest request, int jobId, Uri createdUri) {
    final String description = mContext.getString(R.string.importing_vcard_finished_title, request.displayName);
    final Intent intent;
    if (createdUri != null) {
        final long rawContactId = ContentUris.parseId(createdUri);
        final Uri contactUri = RawContacts.getContactLookupUri(mContext.getContentResolver(),
                ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId));
        intent = new Intent(Intent.ACTION_VIEW, contactUri);
    } else {/*from ww  w  . j  ava 2  s . c  o  m*/
        intent = new Intent(Intent.ACTION_VIEW);
        intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
    }
    intent.setPackage(mContext.getPackageName());
    final Notification notification = NotificationImportExportListener.constructFinishNotification(mContext,
            description, null, intent);
    mNotificationManager.notify(NotificationImportExportListener.DEFAULT_NOTIFICATION_TAG, jobId, notification);
}

From source file:com.manning.androidhacks.hack043.provider.BatchNumbersContentProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    ContentValues values;/*from   w w w .  ja  va  2 s.co m*/
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }
    String table = null;
    String nullableCol = null;

    switch (sUriMatcher.match(uri)) {
    case ITEM:
        table = TABLE_NAME;
        break;
    default:
        new RuntimeException("Invalid URI for inserting: " + uri);
    }

    SQLiteDatabase db = dbHelper.getWritableDatabase();
    long rowId = db.insert(table, nullableCol, values);

    if (rowId > 0) {
        Uri noteUri = ContentUris.withAppendedId(uri, rowId);
        getContext().getContentResolver().notifyChange(noteUri, null);
        return noteUri;
    }

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

From source file:com.laevatein.internal.ui.ImagePreviewActivity.java

@Override
public void onLoad(Cursor cursor) {
    List<Uri> uris = new ArrayList<>();
    while (cursor.moveToNext()) {
        final Item item = Item.valueOf(cursor);
        Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, item.getId());
        uris.add(uri);/*w  ww .  j a  v a 2 s .  c om*/
    }
    PreviewPagerAdapter adapter = (PreviewPagerAdapter) mPager.getAdapter();
    adapter.addAll(uris);
    adapter.notifyDataSetChanged();
    if (!mIsAlreadySetPosition) {
        //onLoad is called many times..
        mIsAlreadySetPosition = true;
        Item selected = getIntent().getParcelableExtra(EXTRA_ITEM);
        int selectedIndex = uris.indexOf(selected.buildContentUri());
        mPager.setCurrentItem(selectedIndex, false);
    }
}

From source file:com.android.email.mail.transport.Rfc822Output.java

/**
 * Write the entire message to an output stream.  This method provides buffering, so it is
 * not necessary to pass in a buffered output stream here.
 *
 * @param context system context for accessing the provider
 * @param messageId the message to write out
 * @param out the output stream to write the message to
 * @param appendQuotedText whether or not to append quoted text if this is a reply/forward
 *
 * TODO alternative parts (e.g. text+html) are not supported here.
 *///from   w w  w .  j  ava 2 s  .  c  o m
public static void writeTo(Context context, long messageId, OutputStream out, boolean appendQuotedText,
        boolean sendBcc) throws IOException, MessagingException {
    Message message = Message.restoreMessageWithId(context, messageId);
    if (message == null) {
        // throw something?
        return;
    }

    OutputStream stream = new BufferedOutputStream(out, 1024);
    Writer writer = new OutputStreamWriter(stream);

    // Write the fixed headers.  Ordering is arbitrary (the legacy code iterated through a
    // hashmap here).

    String date = mDateFormat.format(new Date(message.mTimeStamp));
    writeHeader(writer, "Date", date);

    writeEncodedHeader(writer, "Subject", message.mSubject);

    writeHeader(writer, "Message-ID", message.mMessageId);

    writeAddressHeader(writer, "From", message.mFrom);
    writeAddressHeader(writer, "To", message.mTo);
    writeAddressHeader(writer, "Cc", message.mCc);
    // Address fields.  Note that we skip bcc unless the sendBcc argument is true
    // SMTP should NOT send bcc headers, but EAS must send it!
    if (sendBcc) {
        writeAddressHeader(writer, "Bcc", message.mBcc);
    }
    writeAddressHeader(writer, "Reply-To", message.mReplyTo);
    writeHeader(writer, "MIME-Version", "1.0");

    // Analyze message and determine if we have multiparts
    String text = buildBodyText(context, message, appendQuotedText);

    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId);
    Cursor attachmentsCursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null,
            null, null);

    try {
        int attachmentCount = attachmentsCursor.getCount();
        boolean multipart = attachmentCount > 0;
        String multipartBoundary = null;
        String multipartType = "mixed";

        // Simplified case for no multipart - just emit text and be done.
        if (!multipart) {
            if (text != null) {
                writeTextWithHeaders(writer, stream, text);
            } else {
                writer.write("\r\n"); // a truly empty message
            }
        } else {
            // continue with multipart headers, then into multipart body
            multipartBoundary = "--_com.android.email_" + System.nanoTime();

            // Move to the first attachment; this must succeed because multipart is true
            attachmentsCursor.moveToFirst();
            if (attachmentCount == 1) {
                // If we've got one attachment and it's an ics "attachment", we want to send
                // this as multipart/alternative instead of multipart/mixed
                int flags = attachmentsCursor.getInt(Attachment.CONTENT_FLAGS_COLUMN);
                if ((flags & Attachment.FLAG_ICS_ALTERNATIVE_PART) != 0) {
                    multipartType = "alternative";
                }
            }

            writeHeader(writer, "Content-Type",
                    "multipart/" + multipartType + "; boundary=\"" + multipartBoundary + "\"");
            // Finish headers and prepare for body section(s)
            writer.write("\r\n");

            // first multipart element is the body
            if (text != null) {
                writeBoundary(writer, multipartBoundary, false);
                writeTextWithHeaders(writer, stream, text);
            }

            // Write out the attachments until we run out
            do {
                writeBoundary(writer, multipartBoundary, false);
                Attachment attachment = Attachment.getContent(attachmentsCursor, Attachment.class);
                writeOneAttachment(context, writer, stream, attachment);
                writer.write("\r\n");
            } while (attachmentsCursor.moveToNext());

            // end of multipart section
            writeBoundary(writer, multipartBoundary, true);
        }
    } finally {
        attachmentsCursor.close();
    }

    writer.flush();
    out.flush();
}

From source file:com.mwebster.iemail.mail.transport.Rfc822Output.java

/**
 * Write the entire message to an output stream.  This method provides buffering, so it is
 * not necessary to pass in a buffered output stream here.
 *
 * @param context system context for accessing the provider
 * @param messageId the message to write out
 * @param out the output stream to write the message to
 * @param appendQuotedText whether or not to append quoted text if this is a reply/forward
 *
 * TODO alternative parts (e.g. text+html) are not supported here.
 *//*from ww  w .j av a  2 s.com*/
public static void writeTo(Context context, long messageId, OutputStream out, boolean appendQuotedText,
        boolean sendBcc) throws IOException, MessagingException {
    Message message = Message.restoreMessageWithId(context, messageId);
    if (message == null) {
        // throw something?
        return;
    }

    OutputStream stream = new BufferedOutputStream(out, 1024);
    Writer writer = new OutputStreamWriter(stream);

    // Write the fixed headers.  Ordering is arbitrary (the legacy code iterated through a
    // hashmap here).

    String date = mDateFormat.format(new Date(message.mTimeStamp));
    writeHeader(writer, "Date", date);

    writeEncodedHeader(writer, "Subject", message.mSubject);

    writeHeader(writer, "Message-ID", message.mMessageId);

    writeAddressHeader(writer, "From", message.mFrom);
    writeAddressHeader(writer, "To", message.mTo);
    writeAddressHeader(writer, "Cc", message.mCc);
    // Address fields.  Note that we skip bcc unless the sendBcc argument is true
    // SMTP should NOT send bcc headers, but EAS must send it!
    if (sendBcc) {
        writeAddressHeader(writer, "Bcc", message.mBcc);
    }
    writeAddressHeader(writer, "Reply-To", message.mReplyTo);
    writeHeader(writer, "MIME-Version", "1.0");

    // Analyze message and determine if we have multiparts
    String text = buildBodyText(context, message, appendQuotedText);

    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId);
    Cursor attachmentsCursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null,
            null, null);

    try {
        int attachmentCount = attachmentsCursor.getCount();
        boolean multipart = attachmentCount > 0;
        String multipartBoundary = null;
        String multipartType = "mixed";

        // Simplified case for no multipart - just emit text and be done.
        if (!multipart) {
            if (text != null) {
                writeTextWithHeaders(writer, stream, text);
            } else {
                writer.write("\r\n"); // a truly empty message
            }
        } else {
            // continue with multipart headers, then into multipart body
            multipartBoundary = "--_com.mwebster.iemail." + System.nanoTime();

            // Move to the first attachment; this must succeed because multipart is true
            attachmentsCursor.moveToFirst();
            if (attachmentCount == 1) {
                // If we've got one attachment and it's an ics "attachment", we want to send
                // this as multipart/alternative instead of multipart/mixed
                int flags = attachmentsCursor.getInt(Attachment.CONTENT_FLAGS_COLUMN);
                if ((flags & Attachment.FLAG_ICS_ALTERNATIVE_PART) != 0) {
                    multipartType = "alternative";
                }
            }

            writeHeader(writer, "Content-Type",
                    "multipart/" + multipartType + "; boundary=\"" + multipartBoundary + "\"");
            // Finish headers and prepare for body section(s)
            writer.write("\r\n");

            // first multipart element is the body
            if (text != null) {
                writeBoundary(writer, multipartBoundary, false);
                writeTextWithHeaders(writer, stream, text);
            }

            // Write out the attachments until we run out
            do {
                writeBoundary(writer, multipartBoundary, false);
                Attachment attachment = Attachment.getContent(attachmentsCursor, Attachment.class);
                writeOneAttachment(context, writer, stream, attachment);
                writer.write("\r\n");
            } while (attachmentsCursor.moveToNext());

            // end of multipart section
            writeBoundary(writer, multipartBoundary, true);
        }
    } finally {
        attachmentsCursor.close();
    }

    writer.flush();
    out.flush();
}

From source file:com.example.android.inventoryapp.CatalogActivity.java

public void onItemClick(long id) {
    Intent intent = new Intent(CatalogActivity.this, DetailAcitvity.class);

    Uri currentProductUri = ContentUris.withAppendedId(InventoryContract.ItemEntry.CONTENT_URI, id);
    intent.setData(currentProductUri);//from  ww  w . j  a  v a2  s . co m

    startActivity(intent);
}

From source file:com.google.android.demos.jamendo.app.AlbumActivity.java

private void share() {
    long id = ContentUris.parseId(getIntent().getData());
    Uri uri = ContentUris.withAppendedId(BASE_URI, id);
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    Cursor cursor = mHeaderAdapter.getCursor();
    if (cursor != null && cursor.moveToFirst()) {
        String albumName = cursor.getString(cursor.getColumnIndexOrThrow(Albums.NAME));
        String artistName = cursor.getString(cursor.getColumnIndexOrThrow(Artists.NAME));
        String template = getString(R.string.jamendo_template_album_artist);
        String subject = MessageFormat.format(template, albumName, artistName);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    }//from   w  w  w.j av a  2  s  . c o m
    intent.putExtra(Intent.EXTRA_TEXT, String.valueOf(uri));
    intent = Intent.createChooser(intent, null);
    startActivity(intent);
}