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:bander.notepad.NoteListAppCompat.java

/**
 * Delete a note, confirm when preferred.
 *
 * @param context Context to use.//from   www.j  a va  2 s  . c om
 * @param id      ID of the note to delete.
 */
private void deleteNote(Context context, long id) {
    final long noteId = id;
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    boolean deleteConfirmation = preferences.getBoolean("deleteConfirmation", true);
    if (deleteConfirmation) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).setTitle(R.string.dialog_delete)
                .setMessage(R.string.delete_confirmation)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    // OnClickListener
                    public void onClick(DialogInterface dialog, int which) {
                        Uri noteUri = ContentUris.withAppendedId(Note.CONTENT_URI, noteId);
                        getContentResolver().delete(noteUri, null, null);
                    }
                }).setNegativeButton(android.R.string.cancel, null).create();
        alertDialog.show();
    } else {
        Uri noteUri = ContentUris.withAppendedId(Note.CONTENT_URI, noteId);
        getContentResolver().delete(noteUri, null, null);
    }
}

From source file:edu.cens.loci.ui.PlaceListActivity.java

private Uri getSelectedUri(int position) {
    if (position == ListView.INVALID_POSITION) {
        throw new IllegalArgumentException("Position not in list bound");
    }/*  w  w w  .  j  a v  a2 s.  c o m*/
    final long placeId = mList.get(position).placeId;
    return ContentUris.withAppendedId(Places.CONTENT_URI, placeId);
}

From source file:com.smarthome.deskclock.Alarms.java

private static void enableAlarmInternal(final Context context, final Alarm alarm, boolean enabled) {
    if (alarm == null) {
        return;/*from   ww  w.  java  2 s  .c  o  m*/
    }
    ContentResolver resolver = context.getContentResolver();

    ContentValues values = new ContentValues(2);
    values.put(Alarm.Columns.ENABLED, enabled ? 1 : 0);

    // If we are enabling the alarm, calculate alarm time since the time
    // value in Alarm may be old.
    if (enabled) {
        long time = 0;
        if (!alarm.daysOfWeek.isRepeatSet()) {
            time = calculateAlarm(alarm);
        }
        values.put(Alarm.Columns.ALARM_TIME, time);
    } else {
        // Clear the snooze if the id matches.
        disableSnoozeAlert(context, alarm.id);
    }

    resolver.update(ContentUris.withAppendedId(Alarm.Columns.CONTENT_URI, alarm.id), values, null, null);
}

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

@Override
public void populate(Resource resource) throws LocalStorageException {
    Event e = (Event) resource;

    try {//w  w w.j a  va  2s  .  c o m
        @Cleanup
        Cursor cursor = providerClient.query(ContentUris.withAppendedId(entriesURI(), e.getLocalID()),
                new String[] { /*  0 */ Events.TITLE, Events.EVENT_LOCATION, Events.DESCRIPTION,
                        /*  3 */ Events.DTSTART, Events.DTEND, Events.EVENT_TIMEZONE, Events.EVENT_END_TIMEZONE,
                        Events.ALL_DAY, /*  8 */ Events.STATUS, Events.ACCESS_LEVEL, /* 10 */ Events.RRULE,
                        Events.RDATE, Events.EXRULE, Events.EXDATE, /* 14 */ Events.HAS_ATTENDEE_DATA,
                        Events.ORGANIZER, Events.SELF_ATTENDEE_STATUS, /* 17 */ entryColumnUID(),
                        Events.DURATION, Events.AVAILABILITY },
                null, null, null);
        if (cursor != null && cursor.moveToNext()) {
            e.setUid(cursor.getString(17));

            e.setSummary(cursor.getString(0));
            e.setLocation(cursor.getString(1));
            e.setDescription(cursor.getString(2));

            boolean allDay = cursor.getInt(7) != 0;
            long tsStart = cursor.getLong(3), tsEnd = cursor.getLong(4);
            String duration = cursor.getString(18);

            String tzId = null;
            if (allDay) {
                e.setDtStart(tsStart, null);
                // provide only DTEND and not DURATION for all-day events
                if (tsEnd == 0) {
                    Dur dur = new Dur(duration);
                    java.util.Date dEnd = dur.getTime(new java.util.Date(tsStart));
                    tsEnd = dEnd.getTime();
                }
                e.setDtEnd(tsEnd, null);

            } else {
                // use the start time zone for the end time, too
                // because apps like Samsung Planner allow the user to change "the" time zone but change the start time zone only
                tzId = cursor.getString(5);
                e.setDtStart(tsStart, tzId);
                if (tsEnd != 0)
                    e.setDtEnd(tsEnd, tzId);
                else if (!StringUtils.isEmpty(duration))
                    e.setDuration(new Duration(new Dur(duration)));
            }

            // recurrence
            try {
                String strRRule = cursor.getString(10);
                if (!StringUtils.isEmpty(strRRule))
                    e.setRrule(new RRule(strRRule));

                String strRDate = cursor.getString(11);
                if (!StringUtils.isEmpty(strRDate)) {
                    RDate rDate = new RDate();
                    rDate.setValue(strRDate);
                    e.setRdate(rDate);
                }

                String strExRule = cursor.getString(12);
                if (!StringUtils.isEmpty(strExRule)) {
                    ExRule exRule = new ExRule();
                    exRule.setValue(strExRule);
                    e.setExrule(exRule);
                }

                String strExDate = cursor.getString(13);
                if (!StringUtils.isEmpty(strExDate)) {
                    // ignored, see https://code.google.com/p/android/issues/detail?id=21426
                    ExDate exDate = new ExDate();
                    exDate.setValue(strExDate);
                    e.setExdate(exDate);
                }
            } catch (ParseException ex) {
                Log.w(TAG, "Couldn't parse recurrence rules, ignoring", ex);
            } catch (IllegalArgumentException ex) {
                Log.w(TAG, "Invalid recurrence rules, ignoring", ex);
            }

            // status
            switch (cursor.getInt(8)) {
            case Events.STATUS_CONFIRMED:
                e.setStatus(Status.VEVENT_CONFIRMED);
                break;
            case Events.STATUS_TENTATIVE:
                e.setStatus(Status.VEVENT_TENTATIVE);
                break;
            case Events.STATUS_CANCELED:
                e.setStatus(Status.VEVENT_CANCELLED);
            }

            // availability
            e.setOpaque(cursor.getInt(19) != Events.AVAILABILITY_FREE);

            // attendees
            if (cursor.getInt(14) != 0) { // has attendees
                try {
                    e.setOrganizer(new Organizer(new URI("mailto", cursor.getString(15), null)));
                } catch (URISyntaxException ex) {
                    Log.e(TAG, "Error when creating ORGANIZER URI, ignoring", ex);
                }
                populateAttendees(e);
            }

            // classification
            switch (cursor.getInt(9)) {
            case Events.ACCESS_CONFIDENTIAL:
            case Events.ACCESS_PRIVATE:
                e.setForPublic(false);
                break;
            case Events.ACCESS_PUBLIC:
                e.setForPublic(true);
            }

            populateReminders(e);
        } else
            throw new RecordNotFoundException();
    } catch (RemoteException ex) {
        throw new LocalStorageException(ex);
    }
}

From source file:com.keithandthegirl.services.download.DownloadService.java

private void savePodcast(Long id, String title, String urlPath, File output) {
    Log.v(TAG, "savePodcast : enter");

    sendNotification("Downloading Episode: " + title);

    URL url;/*from   w w  w.  j  av  a 2 s  .co  m*/
    URLConnection con;
    InputStream is;
    FileOutputStream fos;
    byte[] buffer = new byte[4096];

    try {
        url = new URL(urlPath);
        con = url.openConnection();
        is = con.getInputStream();
        fos = new FileOutputStream(output);

        boolean notified = false;
        int length = con.getContentLength();
        int total = 0, read = -1;
        while ((read = is.read(buffer)) != -1) {
            fos.write(buffer, 0, read);

            total += read;

            int percent = (int) FloatMath.ceil(((100 * (float) total) / (float) length));
            //Log.v( TAG, "savePodcast : download percent=" + percent + "%" );
            if (percent % 5 == 0 && !notified) {
                progressUpdate(percent);
                notified = true;
            } else {
                notified = false;
            }
        }
        is.close();
        fos.close();

        result = FragmentActivity.RESULT_OK;

        ContentValues values = new ContentValues();
        values.put(EpisodeConstants.FIELD_FILE, output.getAbsolutePath());

        getContentResolver().update(ContentUris.withAppendedId(EpisodeConstants.CONTENT_URI, id), values, null,
                null);

    } catch (Exception e) {
        Log.e(TAG, "savePodcast : error", e);
    } finally {
        completed();
    }

    Log.v(TAG, "savePodcast : exit");
}

From source file:at.bitfire.davdroid.syncadapter.ContactsSyncManager.java

@Override
protected void prepareDirty() throws CalendarStorageException, ContactsStorageException {
    super.prepareDirty();

    LocalAddressBook addressBook = localAddressBook();

    if (groupMethod == GroupMethod.CATEGORIES) {
        /* groups memberships are represented as contact CATEGORIES */

        // groups with DELETED=1: set all members to dirty, then remove group
        for (LocalGroup group : addressBook.getDeletedGroups()) {
            App.log.fine("Finally removing group " + group);
            // useless because Android deletes group memberships as soon as a group is set to DELETED:
            // group.markMembersDirty();
            group.delete();// w  ww .j  a  v a2s.c o m
        }

        // groups with DIRTY=1: mark all memberships as dirty, then clean DIRTY flag of group
        for (LocalGroup group : addressBook.getDirtyGroups()) {
            App.log.fine("Marking members of modified group " + group + " as dirty");
            group.markMembersDirty();
            group.clearDirty(null);
        }
    } else {
        /* groups as separate VCards: there are group contacts and individual contacts */

        // mark groups with changed members as dirty
        BatchOperation batch = new BatchOperation(addressBook.provider);
        for (LocalContact contact : addressBook.getDirtyContacts())
            try {
                App.log.fine("Looking for changed group memberships of contact " + contact.getFileName());
                Set<Long> cachedGroups = contact.getCachedGroupMemberships(),
                        currentGroups = contact.getGroupMemberships();
                for (Long groupID : SetUtils.disjunction(cachedGroups, currentGroups)) {
                    App.log.fine("Marking group as dirty: " + groupID);
                    batch.enqueue(new BatchOperation.Operation(ContentProviderOperation
                            .newUpdate(addressBook
                                    .syncAdapterURI(ContentUris.withAppendedId(Groups.CONTENT_URI, groupID)))
                            .withValue(Groups.DIRTY, 1).withYieldAllowed(true)));
                }
            } catch (FileNotFoundException ignored) {
            }
        batch.commit();
    }
}

From source file:info.guardianproject.otr.app.im.app.DatabaseUtils.java

/** Update the data of a plugin provider. */
private static int updateProviderRow(ContentResolver cr, long providerId, String providerFullName,
        String signUpUrl) {/*  w  ww  .ja  va2  s . c om*/
    // Update the full name, signup url and category each time when the plugin change
    // instead of specific version change because this is called only once.
    // It's ok to update them even the values are not changed.
    // Note that we don't update the provider name because it's used as
    // identifier at some place and the plugin should never change it.
    ContentValues values = new ContentValues(3);
    values.put(Imps.Provider.FULLNAME, providerFullName);
    values.put(Imps.Provider.SIGNUP_URL, signUpUrl);
    values.put(Imps.Provider.CATEGORY, ImApp.IMPS_CATEGORY);
    Uri uri = ContentUris.withAppendedId(Imps.Provider.CONTENT_URI, providerId);
    return cr.update(uri, values, null, null);
}

From source file:com.guayaba.tapir.ui.fragments.PlaylistFragment.java

/**
 * Create a new {@link AlertDialog} for easy playlist deletion
 * /*w  w  w .  ja v a 2  s.  c  o m*/
 * @param context The {@link Context} to use
 * @param title The title of the playlist being deleted
 * @param id The ID of the playlist being deleted
 * @return A new {@link AlertDialog} used to delete playlists
 */
private final AlertDialog buildDeleteDialog() {
    return new AlertDialog.Builder(getActivity())
            .setTitle(getString(R.string.delete_dialog_title, mPlaylist.mPlaylistName))
            .setPositiveButton(R.string.context_menu_delete, new OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    final Uri mUri = ContentUris.withAppendedId(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
                            mPlaylist.mPlaylistId);
                    getActivity().getContentResolver().delete(mUri, null, null);
                    MusicUtils.refresh();
                }
            }).setNegativeButton(R.string.cancel, new OnClickListener() {

                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    dialog.dismiss();
                }
            }).setMessage(R.string.cannot_be_undone).create();
}

From source file:com.android.emailcommon.provider.EmailContent.java

public Uri getUri() {
    if (mUri == null) {
        mUri = ContentUris.withAppendedId(mBaseUri, mId);
    }
    return mUri;
}

From source file:com.android.emailcommon.provider.EmailContent.java

public static <T extends EmailContent> T restoreContentWithId(final Context context, final Class<T> klass,
        final Uri contentUri, final String[] contentProjection, final long id, final ContentObserver observer) {
    warnIfUiThread();/*from   www . j av a  2s  .  co  m*/
    final Uri u = ContentUris.withAppendedId(contentUri, id);
    final Cursor c = context.getContentResolver().query(u, contentProjection, null, null, null);
    if (c == null)
        throw new ProviderUnavailableException();
    try {
        if (c.moveToFirst()) {
            final T content = getContent(context, c, klass);
            if (observer != null) {
                content.registerObserver(context, observer);
            }
            return content;
        } else {
            return null;
        }
    } finally {
        c.close();
    }
}