Example usage for android.content ContentResolver delete

List of usage examples for android.content ContentResolver delete

Introduction

In this page you can find the example usage for android.content ContentResolver delete.

Prototype

public final int delete(@RequiresPermission.Write @NonNull Uri url, @Nullable String where,
        @Nullable String[] selectionArgs) 

Source Link

Document

Deletes row(s) specified by a content URI.

Usage

From source file:org.mariotaku.twidere.fragment.support.UserProfileFragment.java

private boolean handleMenuItemClick(final MenuItem item) {
    final AsyncTwitterWrapper twitter = getTwitterWrapper();
    final ParcelableUser user = mUser;
    final Relationship relationship = mFriendship;
    if (user == null || twitter == null)
        return false;
    switch (item.getItemId()) {
    case MENU_BLOCK: {
        if (mFriendship != null) {
            if (mFriendship.isSourceBlockingTarget()) {
                twitter.destroyBlockAsync(user.account_id, user.id);
            } else {
                CreateUserBlockDialogFragment.show(getFragmentManager(), user);
            }//from  w  w w  . j a  v  a  2s.c o m
        }
        break;
    }
    case MENU_REPORT_SPAM: {
        ReportSpamDialogFragment.show(getFragmentManager(), user);
        break;
    }
    case MENU_MUTE_USER: {
        final ContentResolver resolver = getContentResolver();
        resolver.delete(Filters.Users.CONTENT_URI, Where.equals(Filters.Users.USER_ID, user.id).getSQL(), null);
        resolver.insert(Filters.Users.CONTENT_URI, makeFilterdUserContentValues(user));
        showInfoMessage(getActivity(), R.string.user_muted, false);
        break;
    }
    case MENU_MENTION: {
        final Intent intent = new Intent(INTENT_ACTION_MENTION);
        final Bundle bundle = new Bundle();
        bundle.putParcelable(EXTRA_USER, user);
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_SEND_DIRECT_MESSAGE: {
        final Uri.Builder builder = new Uri.Builder();
        builder.scheme(SCHEME_TWIDERE);
        builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION);
        builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(user.account_id));
        builder.appendQueryParameter(QUERY_PARAM_RECIPIENT_ID, String.valueOf(user.id));
        startActivity(new Intent(Intent.ACTION_VIEW, builder.build()));
        break;
    }
    case MENU_SET_COLOR: {
        final Intent intent = new Intent(getActivity(), ColorPickerDialogActivity.class);
        intent.putExtra(EXTRA_COLOR, getUserColor(getActivity(), user.id, true));
        intent.putExtra(EXTRA_ALPHA_SLIDER, false);
        intent.putExtra(EXTRA_CLEAR_BUTTON, true);
        startActivityForResult(intent, REQUEST_SET_COLOR);
        break;
    }
    case MENU_CLEAR_NICKNAME: {
        clearUserNickname(getActivity(), user.id);
        break;
    }
    case MENU_SET_NICKNAME: {
        final String nick = getUserNickname(getActivity(), user.id, true);
        SetUserNicknameDialogFragment.show(getFragmentManager(), user.id, nick);
        break;
    }
    case MENU_ADD_TO_LIST: {
        final Intent intent = new Intent(INTENT_ACTION_SELECT_USER_LIST);
        intent.setClass(getActivity(), UserListSelectorActivity.class);
        intent.putExtra(EXTRA_ACCOUNT_ID, user.account_id);
        intent.putExtra(EXTRA_SCREEN_NAME, getAccountScreenName(getActivity(), user.account_id));
        startActivityForResult(intent, REQUEST_ADD_TO_LIST);
        break;
    }
    case MENU_OPEN_WITH_ACCOUNT: {
        final Intent intent = new Intent(INTENT_ACTION_SELECT_ACCOUNT);
        intent.setClass(getActivity(), AccountSelectorActivity.class);
        intent.putExtra(EXTRA_SINGLE_SELECTION, true);
        startActivityForResult(intent, REQUEST_SELECT_ACCOUNT);
        break;
    }
    case MENU_EDIT: {
        final Bundle extras = new Bundle();
        extras.putLong(EXTRA_ACCOUNT_ID, user.account_id);
        final Intent intent = new Intent(INTENT_ACTION_EDIT_USER_PROFILE);
        intent.setClass(getActivity(), UserProfileEditorActivity.class);
        intent.putExtras(extras);
        startActivity(intent);
        return true;
    }
    case MENU_FOLLOW: {
        if (relationship == null)
            return false;
        final boolean isFollowing = relationship.isSourceFollowingTarget();
        final boolean isCreatingFriendship = twitter.isCreatingFriendship(user.account_id, user.id);
        final boolean isDestroyingFriendship = twitter.isDestroyingFriendship(user.account_id, user.id);
        if (!isCreatingFriendship && !isDestroyingFriendship) {
            if (isFollowing) {
                DestroyFriendshipDialogFragment.show(getFragmentManager(), user);
            } else {
                twitter.createFriendshipAsync(user.account_id, user.id);
            }
        }
        return true;
    }
    default: {
        if (item.getIntent() != null) {
            try {
                startActivity(item.getIntent());
            } catch (final ActivityNotFoundException e) {
                Log.w(LOGTAG, e);
                return false;
            }
        }
        break;
    }
    }
    return true;
}

From source file:de.vanita5.twittnuker.fragment.support.UserProfileFragment.java

private boolean handleMenuItemClick(final MenuItem item) {
    final AsyncTwitterWrapper twitter = getTwitterWrapper();
    final ParcelableUser user = mUser;
    final Relationship relationship = mRelationship;
    if (user == null || twitter == null)
        return false;
    switch (item.getItemId()) {
    case MENU_BLOCK: {
        if (mRelationship != null) {
            if (mRelationship.isSourceBlockingTarget()) {
                twitter.destroyBlockAsync(user.account_id, user.id);
            } else {
                CreateUserBlockDialogFragment.show(getFragmentManager(), user);
            }/*  w  ww . j  a  v  a  2 s  .c o  m*/
        }
        break;
    }
    case MENU_REPORT_SPAM: {
        ReportSpamDialogFragment.show(getFragmentManager(), user);
        break;
    }
    case MENU_ADD_TO_FILTER: {
        final ContentResolver resolver = getContentResolver();
        resolver.delete(Filters.Users.CONTENT_URI, Where.equals(Filters.Users.USER_ID, user.id).getSQL(), null);
        resolver.insert(Filters.Users.CONTENT_URI, makeFilterdUserContentValues(user));
        showInfoMessage(getActivity(), R.string.message_user_muted, false);
        break;
    }
    case MENU_MENTION: {
        final Intent intent = new Intent(INTENT_ACTION_MENTION);
        final Bundle bundle = new Bundle();
        bundle.putParcelable(EXTRA_USER, user);
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_SEND_DIRECT_MESSAGE: {
        final Uri.Builder builder = new Uri.Builder();
        builder.scheme(SCHEME_TWITTNUKER);
        builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION);
        builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(user.account_id));
        builder.appendQueryParameter(QUERY_PARAM_RECIPIENT_ID, String.valueOf(user.id));
        startActivity(new Intent(Intent.ACTION_VIEW, builder.build()));
        break;
    }
    case MENU_SET_COLOR: {
        final Intent intent = new Intent(getActivity(), ColorPickerDialogActivity.class);
        intent.putExtra(EXTRA_COLOR, getUserColor(getActivity(), user.id, true));
        intent.putExtra(EXTRA_ALPHA_SLIDER, false);
        intent.putExtra(EXTRA_CLEAR_BUTTON, true);
        startActivityForResult(intent, REQUEST_SET_COLOR);
        break;
    }
    case MENU_CLEAR_NICKNAME: {
        clearUserNickname(getActivity(), user.id);
        break;
    }
    case MENU_SET_NICKNAME: {
        final String nick = getUserNickname(getActivity(), user.id, true);
        SetUserNicknameDialogFragment.show(getFragmentManager(), user.id, nick);
        break;
    }
    case MENU_ADD_TO_LIST: {
        final Intent intent = new Intent(INTENT_ACTION_SELECT_USER_LIST);
        intent.setClass(getActivity(), UserListSelectorActivity.class);
        intent.putExtra(EXTRA_ACCOUNT_ID, user.account_id);
        intent.putExtra(EXTRA_SCREEN_NAME, getAccountScreenName(getActivity(), user.account_id));
        startActivityForResult(intent, REQUEST_ADD_TO_LIST);
        break;
    }
    case MENU_OPEN_WITH_ACCOUNT: {
        final Intent intent = new Intent(INTENT_ACTION_SELECT_ACCOUNT);
        intent.setClass(getActivity(), AccountSelectorActivity.class);
        intent.putExtra(EXTRA_SINGLE_SELECTION, true);
        startActivityForResult(intent, REQUEST_SELECT_ACCOUNT);
        break;
    }
    case MENU_EDIT: {
        final Bundle extras = new Bundle();
        extras.putLong(EXTRA_ACCOUNT_ID, user.account_id);
        final Intent intent = new Intent(INTENT_ACTION_EDIT_USER_PROFILE);
        intent.setClass(getActivity(), UserProfileEditorActivity.class);
        intent.putExtras(extras);
        startActivity(intent);
        return true;
    }
    case MENU_FOLLOW: {
        if (relationship == null)
            return false;
        final boolean isFollowing = relationship.isSourceFollowingTarget();
        final boolean isCreatingFriendship = twitter.isCreatingFriendship(user.account_id, user.id);
        final boolean isDestroyingFriendship = twitter.isDestroyingFriendship(user.account_id, user.id);
        if (!isCreatingFriendship && !isDestroyingFriendship) {
            if (isFollowing) {
                DestroyFriendshipDialogFragment.show(getFragmentManager(), user);
            } else {
                twitter.createFriendshipAsync(user.account_id, user.id);
            }
        }
        return true;
    }
    default: {
        if (item.getIntent() != null) {
            try {
                startActivity(item.getIntent());
            } catch (final ActivityNotFoundException e) {
                if (Utils.isDebugBuild())
                    Log.w(LOGTAG, e);
                return false;
            }
        }
        break;
    }
    }
    return true;
}

From source file:com.android.contacts.ContactSaveService.java

private static void removeMembersFromGroup(ContentResolver resolver, long[] rawContactsToRemove, long groupId) {
    if (rawContactsToRemove == null) {
        return;/*  www  . j  a  v  a2 s . c  o  m*/
    }
    for (long rawContactId : rawContactsToRemove) {
        // Apply the delete operation on the data row for the given raw contact's
        // membership in the given group. If no contact matches the provided selection, then
        // nothing will be done. Just continue to the next contact.
        resolver.delete(Data.CONTENT_URI,
                Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID
                        + "=?",
                new String[] { String.valueOf(rawContactId), GroupMembership.CONTENT_ITEM_TYPE,
                        String.valueOf(groupId) });
    }
}

From source file:com.frostwire.android.gui.Librarian.java

private void syncMediaStore(final Context context, byte fileType, Set<File> ignorableFiles) {
    TableFetcher fetcher = TableFetchers.getFetcher(fileType);

    if (fetcher == null) {
        return;//  w w w  .  j  a  va2 s.c  om
    }

    Cursor c = null;
    try {

        ContentResolver cr = context.getContentResolver();

        String where = MediaColumns.DATA + " LIKE ?";
        String[] whereArgs = new String[] { Platforms.data() + "%" };

        c = cr.query(fetcher.getContentUri(), new String[] { MediaColumns._ID, MediaColumns.DATA }, where,
                whereArgs, null);
        if (c == null) {
            return;
        }

        int idCol = c.getColumnIndex(MediaColumns._ID);
        int pathCol = c.getColumnIndex(MediaColumns.DATA);

        List<Integer> ids = new ArrayList<>(0);

        while (c.moveToNext()) {
            int id = Integer.valueOf(c.getString(idCol));
            String path = c.getString(pathCol);

            if (ignorableFiles.contains(new File(path))) {
                ids.add(id);
            }
        }

        cr.delete(fetcher.getContentUri(), MediaColumns._ID + " IN " + buildSet(ids), null);

    } catch (Throwable e) {
        Log.e(TAG, "General failure during sync of MediaStore", e);
    } finally {
        if (c != null) {
            c.close();
        }
    }
}

From source file:com.snda.mymarket.providers.downloads.DownloadService.java

/**
 * Update {@link #mDownloads} to match {@link DownloadProvider} state.
 * Depending on current download state it may enqueue {@link DownloadThread}
 * instances, request {@link DownloadScanner} scans, update user-visible
 * notifications, and/or schedule future actions with {@link AlarmManager}.
 * <p>//  ww w . j a va2s  .c  o m
 * Should only be called from {@link #mUpdateThread} as after being
 * requested through {@link #enqueueUpdate()}.
 * 
 * @return If there are active tasks being processed, as of the database
 *         snapshot taken in this update.
 */
private boolean updateLocked() {
    final long now = mSystemFacade.currentTimeMillis();
    boolean isActive = false;
    long nextActionMillis = Long.MAX_VALUE;
    final Set<Long> staleIds = new HashSet<Long>(mDownloads.size());
    final ContentResolver resolver = getContentResolver();
    final Cursor cursor = resolver.query(Downloads.ALL_DOWNLOADS_CONTENT_URI, null, null, null, null);
    try {
        final DownloadInfo.Reader reader = new DownloadInfo.Reader(resolver, cursor);
        final int idColumn = cursor.getColumnIndexOrThrow(Downloads._ID);
        while (cursor.moveToNext()) {
            final long id = cursor.getLong(idColumn);
            staleIds.remove(id);
            DownloadInfo info = mDownloads.get(id);
            if (info != null) {
                updateDownload(reader, info, now);
            } else {
                info = insertDownloadLocked(reader, now);
            }
            if (info.mDeleted) {
                // Delete download if requested, but only after cleaning up
                if (!TextUtils.isEmpty(info.mMediaProviderUri)) {
                    resolver.delete(Uri.parse(info.mMediaProviderUri), null, null);
                }
                Helpers.deleteFile(getContentResolver(), info.mId, info.mFileName, info.mMimeType);
            } else {
                // Kick off download task if ready
                final boolean activeDownload = info.startIfReady(this.mNotifier);
                final boolean activeScan = info.startScanIfReady(mScanner);
                if (DEBUG_LIFECYCLE && (activeDownload || activeScan)) {
                    Log.v(Constants.TAG, "Download " + info.mId + ": activeDownload=" + activeDownload
                            + ", activeScan=" + activeScan);
                }
                isActive |= activeDownload;
                isActive |= activeScan;
            }
            // Keep track of nearest next action
            nextActionMillis = Math.min(info.nextActionMillis(now), nextActionMillis);
        }
    } finally {
        cursor.close();
    }
    // Clean up stale downloads that disappeared
    for (Long id : staleIds) {
        deleteDownloadLocked(id);
    }
    // Update notifications visible to user
    mNotifier.updateWith(mDownloads);
    // Set alarm when next action is in future. It's okay if the service
    // continues to run in meantime, since it will kick off an update pass.
    if (nextActionMillis > 0 && nextActionMillis < Long.MAX_VALUE) {
        if (Constants.LOGV) {
            Log.v(Constants.TAG, "scheduling start in " + nextActionMillis + "ms");
        }
        final Intent intent = new Intent(Constants.ACTION_RETRY);
        intent.setClass(this, DownloadReceiver.class);
        mAlarmManager.set(AlarmManager.RTC_WAKEUP, now + nextActionMillis,
                PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT));
    }
    return isActive;
}

From source file:com.chen.emailsync.SyncManager.java

static public void alert(Context context, final long id) {
    final SyncManager ssm = INSTANCE;
    checkSyncManagerRunning();/*from   ww  w.  j a v a  2  s  . com*/
    if (id < 0) {
        log("SyncServiceManager alert");
        kick("ping SyncServiceManager");
    } else if (ssm == null) {
        context.startService(new Intent(context, SyncManager.class));
    } else {
        final AbstractSyncService service = ssm.getRunningService(id);
        if (service != null) {
            // Handle alerts in a background thread, as we are typically called from a
            // broadcast receiver, and are therefore running in the UI thread
            String threadName = "SyncServiceManager Alert: ";
            if (service.mMailbox != null) {
                threadName += service.mMailbox.mDisplayName;
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Mailbox m = Mailbox.restoreMailboxWithId(ssm, id);
                    if (m != null) {
                        // We ignore drafts completely (doesn't sync).  Changes in Outbox are
                        // handled in the checkMailboxes loop, so we can ignore these pings.
                        if (sUserLog) {
                            LogUtils.d(TAG, "Alert for mailbox " + id + " (" + m.mDisplayName + ")");
                        }
                        if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) {
                            String[] args = new String[] { Long.toString(m.mId) };
                            ContentResolver resolver = INSTANCE.mResolver;
                            resolver.delete(Message.DELETED_CONTENT_URI, WHERE_MAILBOX_KEY, args);
                            resolver.delete(Message.UPDATED_CONTENT_URI, WHERE_MAILBOX_KEY, args);
                            return;
                        }
                        service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey);
                        service.mMailbox = m;
                        // Send the alarm to the sync service
                        if (!service.alarm()) {
                            // A false return means that we were forced to interrupt the thread
                            // In this case, we release the mailbox so that we can start another
                            // thread to do the work
                            log("Alarm failed; releasing mailbox");
                            synchronized (sSyncLock) {
                                ssm.releaseMailbox(id);
                            }
                            // Shutdown the connection manager; this should close all of our
                            // sockets and generate IOExceptions all around.
                            SyncManager.shutdownConnectionManager();
                        }
                    }
                }
            }, threadName).start();
        }
    }
}

From source file:com.robotoworks.mechanoid.db.SQuery.java

public int delete(Uri uri) {
    ContentResolver resolver = Mechanoid.getContentResolver();
    return resolver.delete(uri, toString(), getArgsArray());
}

From source file:com.robotoworks.mechanoid.db.SQuery.java

public int delete(Uri uri, boolean notifyChange) {

    uri = uri.buildUpon()//from   w  w  w.j  a v  a2 s  .com
            .appendQueryParameter(MechanoidContentProvider.PARAM_NOTIFY, String.valueOf(notifyChange)).build();

    ContentResolver resolver = Mechanoid.getContentResolver();
    return resolver.delete(uri, toString(), getArgsArray());
}

From source file:com.android.leanlauncher.LauncherModel.java

/**
 * Removes the specified items from the database
 * @param context/*from ww w.j av a2 s .  co  m*/
 * @param items
 */
static void deleteItemsFromDatabase(Context context, final ArrayList<? extends ItemInfo> items) {
    final ContentResolver cr = context.getContentResolver();

    Runnable r = new Runnable() {
        public void run() {
            for (ItemInfo item : items) {
                final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
                cr.delete(uri, null, null);

                // Lock on mBgLock *after* the db operation
                synchronized (sBgLock) {
                    switch (item.itemType) {
                    case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
                        sBgWorkspaceItems.remove(item);
                        break;
                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
                        sBgAppWidgets.remove(item);
                        break;
                    }
                    sBgItemsIdMap.remove(item.id);
                }
            }
        }
    };
    runOnWorkerThread(r);
}

From source file:org.mariotaku.twidere.util.DataStoreUtils.java

public static synchronized void cleanDatabasesByItemLimit(final Context context) {
    if (context == null)
        return;//from w w w . j ava 2s.  c  o  m
    final ContentResolver resolver = context.getContentResolver();
    final int itemLimit = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getInt(KEY_DATABASE_ITEM_LIMIT, DEFAULT_DATABASE_ITEM_LIMIT);

    for (final UserKey accountKey : getAccountKeys(context)) {
        // Clean statuses.
        for (final Uri uri : STATUSES_URIS) {
            if (CachedStatuses.CONTENT_URI.equals(uri)) {
                continue;
            }
            final String table = getTableNameByUri(uri);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(Statuses._ID)).from(new Tables(table))
                    .where(Expression.equalsArgs(Statuses.ACCOUNT_KEY))
                    .orderBy(new OrderBy(Statuses.POSITION_KEY, false)).limit(itemLimit);
            final Expression where = Expression.and(Expression.notIn(new Column(Statuses._ID), qb.build()),
                    Expression.equalsArgs(Statuses.ACCOUNT_KEY));
            final String[] whereArgs = { String.valueOf(accountKey), String.valueOf(accountKey) };
            resolver.delete(uri, where.getSQL(), whereArgs);
        }
        for (final Uri uri : ACTIVITIES_URIS) {
            final String table = getTableNameByUri(uri);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(Activities._ID)).from(new Tables(table))
                    .where(Expression.equalsArgs(Activities.ACCOUNT_KEY))
                    .orderBy(new OrderBy(Activities.TIMESTAMP, false)).limit(itemLimit);
            final Expression where = Expression.and(Expression.notIn(new Column(Activities._ID), qb.build()),
                    Expression.equalsArgs(Activities.ACCOUNT_KEY));
            final String[] whereArgs = { String.valueOf(accountKey), String.valueOf(accountKey) };
            resolver.delete(uri, where.getSQL(), whereArgs);
        }
        for (final Uri uri : DIRECT_MESSAGES_URIS) {
            final String table = getTableNameByUri(uri);
            final Expression accountWhere = Expression.equalsArgs(DirectMessages.ACCOUNT_KEY);
            final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
            qb.select(new Column(DirectMessages._ID)).from(new Tables(table)).where(accountWhere)
                    .orderBy(new OrderBy(DirectMessages.MESSAGE_ID, false)).limit(itemLimit * 10);
            final Expression where = Expression.and(
                    Expression.notIn(new Column(DirectMessages._ID), qb.build()),
                    Expression.equalsArgs(DirectMessages.ACCOUNT_KEY));
            final String[] whereArgs = { String.valueOf(accountKey), String.valueOf(accountKey) };
            resolver.delete(uri, where.getSQL(), whereArgs);
        }
    }
    // Clean cached values.
    for (final Uri uri : CACHE_URIS) {
        final String table = getTableNameByUri(uri);
        if (table == null)
            continue;
        final SQLSelectQuery.Builder qb = new SQLSelectQuery.Builder();
        qb.select(new Column(BaseColumns._ID)).from(new Tables(table))
                .orderBy(new OrderBy(BaseColumns._ID, false)).limit(itemLimit * 20);
        final Expression where = Expression.notIn(new Column(BaseColumns._ID), qb.build());
        resolver.delete(uri, where.getSQL(), null);
    }
}