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.abcvoipsip.ui.calllog.CallLogDetailsFragment.java

/**
 * Returns the list of URIs to show./*from w w w  .j a  v  a 2s  .com*/
 * <p>
 * There are two ways the URIs can be provided to the activity: as the data
 * on the intent, or as a list of ids in the call log added as an extra on
 * the URI.
 * <p>
 * If both are available, the data on the intent takes precedence.
 */
private Uri[] getCallLogEntryUris() {
    long[] ids = getArguments().getLongArray(EXTRA_CALL_LOG_IDS);
    Uri[] uris = new Uri[ids.length];
    for (int index = 0; index < ids.length; ++index) {
        uris[index] = ContentUris.withAppendedId(SipManager.CALLLOG_ID_URI_BASE, ids[index]);
    }
    return uris;
}

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

/**
 * Matches the input string against contacts names and addresses.
 *
 * @param resolver        The content resolver.
 * @param input           The user-typed input string.
 * @param addressesRetVal The addresses in the returned result are also returned here
 *                        for faster lookup.  Pass in an empty set.
 * @return Ordered list of all the matched results.  If there are multiple address matches
 * for the same contact, they will be listed together in individual items, with only
 * the first item containing a name/icon.
 *//* w  w  w.j a  v  a 2  s. com*/
private static List<Result> queryContacts(ContentResolver resolver, String input,
        HashSet<String> addressesRetVal) {
    String where = null;
    String[] whereArgs = null;

    // Match any word in contact name or address.
    if (!TextUtils.isEmpty(input)) {
        where = CONTACTS_WHERE;
        String param1 = input + "%";
        String param2 = "% " + input + "%";
        whereArgs = new String[] { param1, param2, param1, param2 };
    }

    // Perform the query.
    Cursor c = resolver.query(CommonDataKinds.StructuredPostal.CONTENT_URI, CONTACTS_PROJECTION, where,
            whereArgs, Contacts.DISPLAY_NAME + " ASC");

    // Process results.  Group together addresses for the same contact.
    try {
        Map<String, List<Result>> nameToAddresses = new HashMap<String, List<Result>>();
        c.moveToPosition(-1);
        while (c.moveToNext()) {
            String name = c.getString(CONTACTS_INDEX_DISPLAY_NAME);
            String address = c.getString(CONTACTS_INDEX_ADDRESS);
            if (name != null) {

                List<Result> addressesForName = nameToAddresses.get(name);
                Result result;
                if (addressesForName == null) {
                    // Determine if there is a photo for the icon.
                    Uri contactPhotoUri = null;
                    if (c.getLong(CONTACTS_INDEX_PHOTO_ID) > 0) {
                        contactPhotoUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
                                c.getLong(CONTACTS_INDEX_CONTACT_ID));
                    }

                    // First listing for a distinct contact should have the name/icon.
                    addressesForName = new ArrayList<Result>();
                    nameToAddresses.put(name, addressesForName);
                    result = new Result(name, address, R.drawable.ic_contact_picture, contactPhotoUri);
                } else {
                    // Do not include name/icon in subsequent listings for the same contact.
                    result = new Result(null, address, null, null);
                }

                addressesForName.add(result);
                addressesRetVal.add(address);
            }
        }

        // Return the list of results.
        List<Result> allResults = new ArrayList<Result>();
        for (List<Result> result : nameToAddresses.values()) {
            allResults.addAll(result);
        }
        return allResults;

    } finally {
        if (c != null) {
            c.close();
        }
    }
}

From source file:com.markupartist.sthlmtraveling.FavoritesFragment.java

private void doSearch(long id, boolean reversed) {
    Uri uri = ContentUris.withAppendedId(Journeys.CONTENT_URI, id);

    Cursor cursor = getActivity().managedQuery(uri, PROJECTION, null, null, null);
    cursor.moveToFirst();//from   w w w. ja va 2 s  . co  m
    JourneyQuery journeyQuery = getJourneyQuery(cursor);

    if (reversed) {
        Planner.Location tmpStartPoint = new Location(journeyQuery.destination);
        Planner.Location tmpEndPoint = new Location(journeyQuery.origin);
        journeyQuery.origin = tmpStartPoint;
        journeyQuery.destination = tmpEndPoint;
    }

    Intent routesIntent = new Intent(getActivity(), RoutesActivity.class);
    routesIntent.putExtra(RoutesActivity.EXTRA_JOURNEY_QUERY, journeyQuery);
    startActivity(routesIntent);
}

From source file:com.mwebster.exchange.EasOutboxService.java

/**
 * Send a single message via EAS/*from www .ja v a 2 s.c  o  m*/
 * Note that we mark messages SEND_FAILED when there is a permanent failure, rather than an
 * IOException, which is handled by SyncManager with retries, backoffs, etc.
 *
 * @param cacheDir the cache directory for this context
 * @param msgId the _id of the message to send
 * @throws IOException
 */
int sendMessage(File cacheDir, long msgId) throws IOException, MessagingException {
    int result;
    sendCallback(msgId, null, EmailServiceStatus.IN_PROGRESS);
    File tmpFile = File.createTempFile("eas_", "tmp", cacheDir);
    // Write the output to a temporary file
    try {
        String[] cols = getRowColumns(Message.CONTENT_URI, msgId, MessageColumns.FLAGS, MessageColumns.SUBJECT);
        int flags = Integer.parseInt(cols[0]);
        String subject = cols[1];

        boolean reply = (flags & Message.FLAG_TYPE_REPLY) != 0;
        boolean forward = (flags & Message.FLAG_TYPE_FORWARD) != 0;
        // The reference message and mailbox are called item and collection in EAS
        String itemId = null;
        String collectionId = null;
        if (reply || forward) {
            // First, we need to get the id of the reply/forward message
            cols = getRowColumns(Body.CONTENT_URI, BODY_SOURCE_PROJECTION, WHERE_MESSAGE_KEY,
                    new String[] { Long.toString(msgId) });
            if (cols != null) {
                long refId = Long.parseLong(cols[0]);
                // Then, we need the serverId and mailboxKey of the message
                cols = getRowColumns(Message.CONTENT_URI, refId, SyncColumns.SERVER_ID,
                        MessageColumns.MAILBOX_KEY);
                if (cols != null) {
                    itemId = cols[0];
                    long boxId = Long.parseLong(cols[1]);
                    // Then, we need the serverId of the mailbox
                    cols = getRowColumns(Mailbox.CONTENT_URI, boxId, MailboxColumns.SERVER_ID);
                    if (cols != null) {
                        collectionId = cols[0];
                    }
                }
            }
        }

        boolean smartSend = itemId != null && collectionId != null;

        // Write the message in rfc822 format to the temporary file
        FileOutputStream fileStream = new FileOutputStream(tmpFile);
        Rfc822Output.writeTo(mContext, msgId, fileStream, !smartSend, true);
        fileStream.close();

        // Now, get an input stream to our temporary file and create an entity with it
        FileInputStream inputStream = new FileInputStream(tmpFile);
        InputStreamEntity inputEntity = new InputStreamEntity(inputStream, tmpFile.length());

        // Create the appropriate command and POST it to the server
        String cmd = "SendMail&SaveInSent=T";
        if (smartSend) {
            cmd = reply ? "SmartReply" : "SmartForward";
            cmd += "&ItemId=" + itemId + "&CollectionId=" + collectionId + "&SaveInSent=T";
        }
        userLog("Send cmd: " + cmd);
        HttpResponse resp = sendHttpClientPost(cmd, inputEntity, SEND_MAIL_TIMEOUT);

        inputStream.close();
        int code = resp.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            userLog("Deleting message...");
            mContentResolver.delete(ContentUris.withAppendedId(Message.CONTENT_URI, msgId), null, null);
            result = EmailServiceStatus.SUCCESS;
            sendCallback(-1, subject, EmailServiceStatus.SUCCESS);
        } else {
            userLog("Message sending failed, code: " + code);
            ContentValues cv = new ContentValues();
            cv.put(SyncColumns.SERVER_ID, SEND_FAILED);
            Message.update(mContext, Message.CONTENT_URI, msgId, cv);
            // We mark the result as SUCCESS on a non-auth failure since the message itself is
            // already marked failed and we don't want to stop other messages from trying to
            // send.
            if (isAuthError(code)) {
                result = EmailServiceStatus.LOGIN_FAILED;
            } else {
                result = EmailServiceStatus.SUCCESS;
            }
            sendCallback(msgId, null, result);

        }
    } catch (IOException e) {
        // We catch this just to send the callback
        sendCallback(msgId, null, EmailServiceStatus.CONNECTION_ERROR);
        throw e;
    } finally {
        // Clean up the temporary file
        if (tmpFile.exists()) {
            tmpFile.delete();
        }
    }
    return result;
}

From source file:com.jefftharris.passwdsafe.SyncProviderFragment.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;//from   w ww. j  av  a2 s  .  c  om
    }

    Uri uri = ContentUris.withAppendedId(PasswdSafeContract.Providers.CONTENT_URI, id);
    itsListener.showSyncProviderFiles(uri);
}

From source file:com.bangz.smartmute.RulelistFragment.java

@Override
public void onActivedButtonClick(long id, boolean bActivited) {
    //Cursor cursor = mAdapter.getCursor();

    LogUtils.LOGD(TAG, "Activited Button clicked. id: " + id + " Activited: " + bActivited);

    ContentResolver cr = getActivity().getContentResolver();
    Uri uri = ContentUris.withAppendedId(RulesColumns.CONTENT_URI, id);

    String[] projects = { RulesColumns.RULETYPE

    };//from  www  . j  av  a  2 s .co m
    Cursor cursor = cr.query(uri, projects, null, null, null);
    cursor.moveToFirst();
    int ruletype = cursor.getInt(cursor.getColumnIndex(RulesColumns.RULETYPE));

    ContentValues contentValues = new ContentValues();
    contentValues.put(RulesColumns.ACTIVATED, bActivited ? 1 : 0);
    cr.update(uri, contentValues, null, null);

    mAdapter.notifyDataSetChanged();

    if (ruletype == RulesColumns.RT_TIME) {
        if (bActivited == false)
            TimeRuleAlarmService.cancelScheduledAlarm(getActivity(), uri);
        else
            TimeRuleAlarmService.startScheduleAlarm(getActivity(), uri);
    } else if (ruletype == RulesColumns.RT_LOCATION) {
        //TODO cancel location mute
    }
}

From source file:com.google.android.apps.muzei.gallery.GalleryArtSource.java

private void publishNextArtwork(Uri forceUri) {
    // schedule next
    scheduleNext();//  w  w  w  . ja v  a 2s .  co  m

    Cursor chosenUris = getContentResolver().query(GalleryContract.ChosenPhotos.CONTENT_URI,
            new String[] { BaseColumns._ID }, null, null, null);
    int numChosenUris = (chosenUris != null) ? chosenUris.getCount() : 0;

    Artwork currentArtwork = getCurrentArtwork();
    String lastToken = (currentArtwork != null) ? currentArtwork.getToken() : null;

    Uri imageUri;
    Random random = new Random();
    if (forceUri != null) {
        imageUri = forceUri;

    } else if (numChosenUris > 0) {
        while (true) {
            chosenUris.moveToPosition(random.nextInt(chosenUris.getCount()));
            imageUri = ContentUris.withAppendedId(GalleryContract.ChosenPhotos.CONTENT_URI,
                    chosenUris.getLong(chosenUris.getColumnIndex(BaseColumns._ID)));
            if (numChosenUris <= 1 || !imageUri.toString().equals(lastToken)) {
                break;
            }
        }
    } else {
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Log.w(TAG, "Missing read external storage permission.");
            return;
        }
        Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.MediaColumns._ID },
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " NOT LIKE '%Screenshots%'", null, null);
        if (cursor == null) {
            Log.w(TAG, "Empty cursor.");
            return;
        }

        int count = cursor.getCount();
        if (count == 0) {
            Log.e(TAG, "No photos in the gallery.");
            return;
        }

        while (true) {
            cursor.moveToPosition(random.nextInt(count));
            imageUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    cursor.getLong(0));
            if (!imageUri.toString().equals(lastToken)) {
                break;
            }
        }

        cursor.close();
    }
    if (chosenUris != null) {
        chosenUris.close();
    }

    String token = imageUri.toString();

    // Retrieve metadata for item
    ensureMetadataExists(imageUri);
    String[] projection = { GalleryContract.MetadataCache.COLUMN_NAME_DATETIME,
            GalleryContract.MetadataCache.COLUMN_NAME_LOCATION };
    Cursor metadata = getContentResolver().query(GalleryContract.MetadataCache.CONTENT_URI, projection,
            GalleryContract.MetadataCache.COLUMN_NAME_URI + "=?", new String[] { imageUri.toString() }, null);
    long datetime = 0;
    String location = null;
    if (metadata != null && metadata.moveToFirst()) {
        datetime = metadata
                .getLong(metadata.getColumnIndex(GalleryContract.MetadataCache.COLUMN_NAME_DATETIME));
        location = metadata
                .getString(metadata.getColumnIndex(GalleryContract.MetadataCache.COLUMN_NAME_LOCATION));
    }
    if (metadata != null) {
        metadata.close();
    }

    // Publish the actual artwork
    String title;
    if (datetime > 0) {
        title = DateUtils.formatDateTime(this, datetime,
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY);
    } else {
        title = getString(R.string.gallery_from_gallery);
    }

    String byline;
    if (!TextUtils.isEmpty(location)) {
        byline = location;
    } else {
        byline = getString(R.string.gallery_touch_to_view);
    }

    publishArtwork(new Artwork.Builder().imageUri(imageUri).title(title).byline(byline).token(token)
            .viewIntent(new Intent(Intent.ACTION_VIEW).setDataAndType(imageUri, "image/jpeg")).build());
}

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

/**
 * Processes all groups with non-null {@link #COLUMN_PENDING_MEMBERS}: the pending memberships
 * are (if possible) applied, keeping cached memberships in sync.
 * @param addressBook    address book to take groups from
 * @throws ContactsStorageException on contact provider errors
 *//*from  w  ww.j a  v  a2s  .  co  m*/
public static void applyPendingMemberships(LocalAddressBook addressBook) throws ContactsStorageException {
    try {
        @Cleanup
        Cursor cursor = addressBook.provider.query(addressBook.syncAdapterURI(Groups.CONTENT_URI),
                new String[] { Groups._ID, COLUMN_PENDING_MEMBERS }, COLUMN_PENDING_MEMBERS + " IS NOT NULL",
                new String[] {}, null);

        BatchOperation batch = new BatchOperation(addressBook.provider);
        while (cursor != null && cursor.moveToNext()) {
            long id = cursor.getLong(0);
            Constants.log.fine("Assigning members to group " + id);

            // delete all memberships and cached memberships for this group
            batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
                    .newDelete(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI))
                    .withSelection(
                            "(" + GroupMembership.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID
                                    + "=?) OR (" + CachedGroupMembership.MIMETYPE + "=? AND "
                                    + CachedGroupMembership.GROUP_ID + "=?)",
                            new String[] { GroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id),
                                    CachedGroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id) })
                    .withYieldAllowed(true)));

            // extract list of member UIDs
            List<String> members = new LinkedList<>();
            byte[] raw = cursor.getBlob(1);
            @Cleanup("recycle")
            Parcel parcel = Parcel.obtain();
            parcel.unmarshall(raw, 0, raw.length);
            parcel.setDataPosition(0);
            parcel.readStringList(members);

            // insert memberships
            for (String uid : members) {
                Constants.log.fine("Assigning member: " + uid);
                try {
                    LocalContact member = addressBook.findContactByUID(uid);
                    member.addToGroup(batch, id);
                } catch (FileNotFoundException e) {
                    Constants.log.log(Level.WARNING, "Group member not found: " + uid, e);
                }
            }

            // remove pending memberships
            batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
                    .newUpdate(addressBook.syncAdapterURI(ContentUris.withAppendedId(Groups.CONTENT_URI, id)))
                    .withValue(COLUMN_PENDING_MEMBERS, null).withYieldAllowed(true)));

            batch.commit();
        }
    } catch (RemoteException e) {
        throw new ContactsStorageException("Couldn't get pending memberships", e);
    }
}

From source file:com.ksk.droidbatterybooster.provider.TimeSchedule.java

/**
 * A convenience method to set an time schedule in the Time Schedule
 * content provider.//w w w  . j a  va2s . c  om
 * @return Time when the time schedule will fire.
 */
public static long setTimeSchedule(Context context, TimeSchedule timeSchedule) {
    ContentValues values = createContentValues(timeSchedule);
    ContentResolver resolver = context.getContentResolver();
    resolver.update(ContentUris.withAppendedId(CONTENT_URI, timeSchedule.id), values, null, null);
    setNextAction(context);
    return calculateTimeSchedule(timeSchedule);
}

From source file:com.android.exchange.EasOutboxService.java

/**
 * Send a single message via EAS/*from w  w  w . ja  va2  s.  c o m*/
 * Note that we mark messages SEND_FAILED when there is a permanent failure, rather than an
 * IOException, which is handled by SyncManager with retries, backoffs, etc.
 *
 * @param cacheDir the cache directory for this context
 * @param msgId the _id of the message to send
 * @throws IOException
 */
int sendMessage(File cacheDir, long msgId) throws IOException, MessagingException {
    int result = EmailServiceStatus.SUCCESS;
    sendCallback(msgId, null, EmailServiceStatus.IN_PROGRESS);
    File tmpFile = File.createTempFile("eas_", "tmp", cacheDir);
    // Write the output to a temporary file
    try {
        String[] cols = getRowColumns(Message.CONTENT_URI, msgId, MessageColumns.FLAGS, MessageColumns.SUBJECT);
        int flags = Integer.parseInt(cols[0]);
        String subject = cols[1];

        boolean reply = (flags & Message.FLAG_TYPE_REPLY) != 0;
        boolean forward = (flags & Message.FLAG_TYPE_FORWARD) != 0;
        // The reference message and mailbox are called item and collection in EAS
        String itemId = null;
        String collectionId = null;
        if (reply || forward) {
            // First, we need to get the id of the reply/forward message
            cols = getRowColumns(Body.CONTENT_URI, BODY_SOURCE_PROJECTION, WHERE_MESSAGE_KEY,
                    new String[] { Long.toString(msgId) });
            if (cols != null) {
                long refId = Long.parseLong(cols[0]);
                // Then, we need the serverId and mailboxKey of the message
                cols = getRowColumns(Message.CONTENT_URI, refId, SyncColumns.SERVER_ID,
                        MessageColumns.MAILBOX_KEY);
                if (cols != null) {
                    itemId = cols[0];
                    long boxId = Long.parseLong(cols[1]);
                    // Then, we need the serverId of the mailbox
                    cols = getRowColumns(Mailbox.CONTENT_URI, boxId, MailboxColumns.SERVER_ID);
                    if (cols != null) {
                        collectionId = cols[0];
                    }
                }
            }
        }

        boolean smartSend = itemId != null && collectionId != null;

        // Write the message in rfc822 format to the temporary file
        FileOutputStream fileStream = new FileOutputStream(tmpFile);
        Rfc822Output.writeTo(mContext, msgId, fileStream, !smartSend, true);
        fileStream.close();

        // Now, get an input stream to our temporary file and create an entity with it
        FileInputStream inputStream = new FileInputStream(tmpFile);
        InputStreamEntity inputEntity = new InputStreamEntity(inputStream, tmpFile.length());

        // Create the appropriate command and POST it to the server
        String cmd = "SendMail&SaveInSent=T";
        if (smartSend) {
            cmd = reply ? "SmartReply" : "SmartForward";
            cmd += "&ItemId=" + itemId + "&CollectionId=" + collectionId + "&SaveInSent=T";
        }
        userLog("Send cmd: " + cmd);
        HttpResponse resp = sendHttpClientPost(cmd, inputEntity, SEND_MAIL_TIMEOUT);

        inputStream.close();
        int code = resp.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            userLog("Deleting message...");
            mContentResolver.delete(ContentUris.withAppendedId(Message.CONTENT_URI, msgId), null, null);
            result = EmailServiceStatus.SUCCESS;
            sendCallback(-1, subject, EmailServiceStatus.SUCCESS);
        } else {
            userLog("Message sending failed, code: " + code);

            boolean retrySuccess = false;
            if (smartSend) {
                userLog("Retrying without smartSend");
                cmd = "SendMail&SaveInSent=T";
                userLog("Send cmd: " + cmd);

                inputStream = new FileInputStream(tmpFile);
                inputEntity = new InputStreamEntity(inputStream, tmpFile.length());

                resp = sendHttpClientPost(cmd, inputEntity, SEND_MAIL_TIMEOUT);

                inputStream.close();
                code = resp.getStatusLine().getStatusCode();
                if (code == HttpStatus.SC_OK) {
                    userLog("Deleting message...");
                    mContentResolver.delete(ContentUris.withAppendedId(Message.CONTENT_URI, msgId), null, null);
                    result = EmailServiceStatus.SUCCESS;
                    sendCallback(-1, subject, EmailServiceStatus.SUCCESS);
                    retrySuccess = true;
                }
            }

            if (!retrySuccess) {
                userLog("Message sending failed, code: " + code);

                ContentValues cv = new ContentValues();
                cv.put(SyncColumns.SERVER_ID, SEND_FAILED);
                Message.update(mContext, Message.CONTENT_URI, msgId, cv);
                // We mark the result as SUCCESS on a non-auth failure since the message itself
                // is already marked failed and we don't want to stop other messages from
                // trying to send.
                if (isAuthError(code)) {
                    result = EmailServiceStatus.LOGIN_FAILED;
                } else {
                    result = EmailServiceStatus.SUCCESS;
                }
                sendCallback(msgId, null, result);
            }

        }
    } catch (IOException e) {
        // We catch this just to send the callback
        sendCallback(msgId, null, EmailServiceStatus.CONNECTION_ERROR);
        throw e;
    } finally {
        // Clean up the temporary file
        if (tmpFile.exists()) {
            tmpFile.delete();
        }
    }
    return result;
}