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.android.contacts.common.model.ContactLoaderTest.java

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

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

    Contact contact = assertLoadContact(lookupNoIdUri);

    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 w w  .  j  av a2 s  .  c  o  m
}

From source file:com.example.android.notepad.NotesList.java

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);

    String action = getIntent().getAction();
    if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
        // The caller is waiting for us to return a note selected by
        // the user.  The have clicked on one, so return it now.
        setResult(RESULT_OK, new Intent().setData(uri));
    } else {/* w w  w .  j  a  va 2 s  .  c  o m*/
        // Launch activity to view/edit the currently selected item
        startActivity(new Intent(Intent.ACTION_EDIT, uri));
    }
}

From source file:com.iceteck.silicompressorr.FileUtils.java

/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.<br>
 * <br>//from  www  . ja va 2 s. c o  m
 * Callers should check whether the path is local before assuming it
 * represents a local file.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @see #isLocal(String)
 * @see #getFile(Context, Uri)
 * @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    if (DEBUG)
        Log.d(TAG + " File -",
                "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", Port: "
                        + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: " + uri.getScheme()
                        + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString());

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {

        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:com.granita.contacticloudsync.resource.LocalCalendar.java

@SuppressWarnings("Recycle")
public void processDirtyExceptions() throws CalendarStorageException {
    // process deleted exceptions
    Constants.log.info("Processing deleted exceptions");
    try {//from w w  w . j a  v a  2 s .com
        @Cleanup
        Cursor cursor = provider.query(syncAdapterURI(Events.CONTENT_URI),
                new String[] { Events._ID, Events.ORIGINAL_ID, LocalEvent.COLUMN_SEQUENCE },
                Events.DELETED + "!=0 AND " + Events.ORIGINAL_ID + " IS NOT NULL", null, null);
        while (cursor != null && cursor.moveToNext()) {
            Constants.log.debug("Found deleted exception, removing; then re-schuling original event");
            long id = cursor.getLong(0), // can't be null (by definition)
                    originalID = cursor.getLong(1); // can't be null (by query)
            int sequence = cursor.isNull(2) ? 0 : cursor.getInt(2);

            // get original event's SEQUENCE
            @Cleanup
            Cursor cursor2 = provider.query(
                    syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID)),
                    new String[] { LocalEvent.COLUMN_SEQUENCE }, null, null, null);
            int originalSequence = cursor.isNull(0) ? 0 : cursor.getInt(0);

            BatchOperation batch = new BatchOperation(provider);
            // re-schedule original event and set it to DIRTY
            batch.enqueue(ContentProviderOperation
                    .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID)))
                    .withValue(LocalEvent.COLUMN_SEQUENCE, originalSequence)
                    .withValue(Events.DIRTY, DIRTY_INCREASE_SEQUENCE).build());
            // remove exception
            batch.enqueue(ContentProviderOperation
                    .newDelete(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, id))).build());
            batch.commit();
        }
    } catch (RemoteException e) {
        throw new CalendarStorageException("Couldn't process locally modified exception", e);
    }

    // process dirty exceptions
    Constants.log.info("Processing dirty exceptions");
    try {
        @Cleanup
        Cursor cursor = provider.query(syncAdapterURI(Events.CONTENT_URI),
                new String[] { Events._ID, Events.ORIGINAL_ID, LocalEvent.COLUMN_SEQUENCE },
                Events.DIRTY + "!=0 AND " + Events.ORIGINAL_ID + " IS NOT NULL", null, null);
        while (cursor != null && cursor.moveToNext()) {
            Constants.log.debug("Found dirty exception, increasing SEQUENCE to re-schedule");
            long id = cursor.getLong(0), // can't be null (by definition)
                    originalID = cursor.getLong(1); // can't be null (by query)
            int sequence = cursor.isNull(2) ? 0 : cursor.getInt(2);

            BatchOperation batch = new BatchOperation(provider);
            // original event to DIRTY
            batch.enqueue(ContentProviderOperation
                    .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, originalID)))
                    .withValue(Events.DIRTY, DIRTY_DONT_INCREASE_SEQUENCE).build());
            // increase SEQUENCE and set DIRTY to 0
            batch.enqueue(ContentProviderOperation
                    .newUpdate(syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, id)))
                    .withValue(LocalEvent.COLUMN_SEQUENCE, sequence + 1).withValue(Events.DIRTY, 0).build());
            batch.commit();
        }
    } catch (RemoteException e) {
        throw new CalendarStorageException("Couldn't process locally modified exception", e);
    }
}

From source file:com.android.emailcommon.internet.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 useSmartReply whether or not quoted text is appended to a reply/forward
 *///from   w w w. j a  va 2  s  . co m
public static void writeTo(Context context, long messageId, OutputStream out, boolean useSmartReply,
        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 = DATE_FORMAT.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
    Body body = Body.restoreBodyWithMessageId(context, message.mId);
    String[] bodyText = buildBodyText(body, message.mFlags, useSmartReply);

    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId);
    Cursor attachmentsCursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION,
            WHERE_NOT_SMART_FORWARD, 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) {
            writeTextWithHeaders(writer, stream, bodyText);
        } else {
            // continue with multipart headers, then into multipart body
            multipartBoundary = getNextBoundary();

            // 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 (bodyText[INDEX_BODY_TEXT] != null) {
                writeBoundary(writer, multipartBoundary, false);
                writeTextWithHeaders(writer, stream, bodyText);
            }

            // 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.hhunj.hhudata.SearchBookContentsActivity.java

public void updatedb(List<SearchBookContentsResult> items) {
    int max_alarm_time_span = 60;
    ContentResolver resolver = getApplicationContext().getContentResolver();

    ContentValues values = new ContentValues();

    for (int i = 0; i < items.size(); i++) {

        SearchBookContentsResult res = items.get(i);
        long stationid = Long.parseLong(res.getPageNumber());

        values.put(NotePad.Notes.TITLE, res.getName());
        values.put(NotePad.Notes.NOTE, "");

        values.put(NotePad.Notes.LONGITUTE, 108.0);
        values.put(NotePad.Notes.LATITUDE, 32.0);
        values.put(NotePad.Notes.SPEED, 55);
        values.put(NotePad.Notes.ALTITUDE, 55);

        values.put(NotePad.Notes.CREATEDDATE, res.getRectime().getTime());

        values.put(NotePad.Notes._ID, stationid);//id

        Uri urlNote = NotePad.Notes.CONTENT_URI;

        Uri myUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, stationid);

        Cursor cur = resolver.query(myUri, NotePad.Notes.PROJECTION, null, null, null);

        if (cur != null && cur.moveToFirst()) {
            try {
                long id = cur.getLong(NotePad.Notes._ID_COLUMN);
                Date oldtime = new Date(cur.getLong(cur.getColumnIndex(NotePad.Notes.CREATEDDATE)));
                boolean oldalarm = (cur.getInt(NotePad.Notes.ALARM_COLUMN) == 0) ? false : true;

                long dif = (res.getRectime().getTime() - oldtime.getTime()) / (60 * 1000);

                dif = ((new Date()).getTime() - oldtime.getTime()) / (60 * 1000);

                if (dif > max_alarm_time_span) {
                    //...
                    if (oldalarm == false) {
                        Log.w(TAG, "over time err--------");
                        String phoneNumber = "13338620269";
                        String message = "over time err--------";
                        sendSMS(phoneNumber, message);
                        values.put(NotePad.Notes.ALARM, true);
                    }//from w  ww .  j a va 2 s. c  o m

                } else {
                    values.put(NotePad.Notes.ALARM, false);
                }

            } catch (Exception e) {
                int aa = 0;

            }

            int count = resolver.update(myUri, values, null, null);
            //  resolver.update( myUri, values, NotePad.Notes._ID + " = " +res.getPageNumber(), null);
            if (count == 0) {

            }
        } else {
            try {
                myUri = resolver.insert(urlNote, values);
            } catch (IllegalArgumentException e) {
                throw e;
            }
        }
    }

}

From source file:edu.mit.mobile.android.locast.data.CastMedia.java

/**
 * @param context/*from w  w w  . j a va  2  s.  c  om*/
 * @param c
 * @param castMediaUri
 *
 */
public static void showMedia(Context context, Cursor c, Uri castMediaUri) {
    final String mediaString = c.getString(c.getColumnIndex(CastMedia._MEDIA_URL));
    final String locMediaString = c.getString(c.getColumnIndex(CastMedia._LOCAL_URI));
    String mimeType = null;

    Uri media;

    if (locMediaString != null) {
        media = Uri.parse(locMediaString);
        if ("file".equals(media.getScheme())) {
            mimeType = c.getString(c.getColumnIndex(CastMedia._MIME_TYPE));
        }

    } else if (mediaString != null) {
        media = Uri.parse(mediaString);
        mimeType = c.getString(c.getColumnIndex(CastMedia._MIME_TYPE));

        // we strip this because we don't really want to force them to go to the browser.
        if ("text/html".equals(mimeType)) {
            mimeType = null;
        }
    } else {
        Log.e(TAG, "asked to show media for " + castMediaUri + " but there was nothing to show");
        return;
    }

    final Intent i = new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(media, mimeType);

    if (mimeType != null && mimeType.startsWith("video/")) {
        context.startActivity(new Intent(Intent.ACTION_VIEW,
                ContentUris.withAppendedId(castMediaUri, c.getLong(c.getColumnIndex(CastMedia._ID)))));
    } else {
        // setting the MIME type for URLs doesn't work.
        try {
            context.startActivity(i);
        } catch (final ActivityNotFoundException e) {
            // try it again, but without a mime type.
            if (mimeType != null) {
                i.setDataAndType(media, null);
            }
            try {
                context.startActivity(i);
            } catch (final ActivityNotFoundException e2) {
                Toast.makeText(context, R.string.error_cast_media_no_activities, Toast.LENGTH_LONG).show();
            }
        }
    }
}

From source file:com.example.android.honeypad.ui.NoteListFragment.java

@Override
public void onItemClick(AdapterView<?> list, View v, int position, long id) {
    if (mMode == null) {
        if (mTwoPaneView) {
            clearActivation();//from   w w  w  . j  a v  a2 s  .  com
            mCurrentActivePosition = position;
            UiUtils.setActivatedCompat(v, true);
        }
        mContainerCallback.onNoteSelected(ContentUris.withAppendedId(NotesProvider.CONTENT_URI, id));
    } else {
        if (mCheckedItems.contains(id)) {
            ((CheckedTextView) v).setChecked(false);
            mCheckedItems.remove(id);
        } else {
            ((CheckedTextView) v).setChecked(true);
            mCheckedItems.add(id);
        }

        if (mCheckedItems.size() > 0) {
            setSelectedCount();
        } else {
            mMode.finish();
        }
    }
}

From source file:bander.notepad.NoteListAppCompat.java

public void onItemClick(AdapterView<?> l, View v, int position, long id) {
    Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);

    String action = getIntent().getAction();
    if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
        setResult(RESULT_OK, new Intent().setData(uri).setClassName(getApplicationContext().getPackageName(),
                "bander.notepad.NoteEditAppCompat"));
    } else {/*from  w w w  .  j a va2  s  .  c  o m*/
        startActivity(new Intent(Intent.ACTION_EDIT, uri).setClassName(getApplicationContext().getPackageName(),
                "bander.notepad.NoteEditAppCompat"));
    }
}

From source file:at.bitfire.ical4android.AndroidTaskList.java

public Uri taskListSyncUri() {
    return syncAdapterURI(ContentUris.withAppendedId(provider.taskListsUri(), id));
}