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:com.dwdesign.tweetings.activity.HomeActivity.java

public void checkAndSendFailedTweets() {
    if (mPreferences.getBoolean(PREFERENCE_KEY_AUTOMATIC_RETRY, false)) {
        ContentResolver mResolver = getContentResolver();

        final String[] cols = Drafts.COLUMNS;
        final Cursor cur = getContentResolver().query(Drafts.CONTENT_URI, cols, null, null, null);
        if (cur != null) {
            cur.moveToFirst();//from www  .j  a  v  a2  s.  co m
            int i = 0;
            while (!cur.isAfterLast()) {
                final DraftItem draft = new DraftItem(cur, i);

                if (draft.is_queued) {
                    final Uri image_uri = draft.media_uri == null ? null : Uri.parse(draft.media_uri);

                    mService.updateStatus(draft.account_ids, draft.text, null, image_uri,
                            draft.in_reply_to_status_id, draft.is_possibly_sensitive,
                            draft.is_photo_attached && !draft.is_image_attached);

                    mResolver.delete(Drafts.CONTENT_URI, Drafts._ID + " = " + draft._id, null);
                }

                i++;
                cur.moveToNext();
            }
            cur.close();
        }
    }
}

From source file:com.dwdesign.tweetings.fragment.UserProfileFragment.java

@Override
public boolean onMenuItemClick(final MenuItem item) {
    if (mUser == null || mService == null)
        return false;
    switch (item.getItemId()) {
    case MENU_TAKE_PHOTO: {
        takePhoto();/*from  ww  w. jav a  2 s. c o m*/
        break;
    }
    case MENU_ADD_IMAGE: {
        pickImage();
        break;
    }
    case MENU_BANNER_TAKE_PHOTO: {
        takeBannerPhoto();
        break;
    }
    case MENU_BANNER_ADD_IMAGE: {
        pickBannerImage();
        break;
    }
    case MENU_TRACKING: {
        UpdateTrackingTask task = new UpdateTrackingTask(!tracking);
        task.execute();
        break;
    }
    case MENU_BLOCK: {
        if (mService == null || mFriendship == null) {
            break;
        }
        if (mFriendship.isSourceBlockingTarget()) {
            mService.destroyBlock(mAccountId, mUser.getId());
        } else {
            mService.createBlock(mAccountId, mUser.getId());
        }
        break;
    }
    case MENU_REPORT_SPAM: {
        mService.reportSpam(mAccountId, mUser.getId());
        break;
    }
    case MENU_MUTE_USER: {
        final String screen_name = mUser.getScreenName();
        final Uri uri = Filters.Users.CONTENT_URI;
        final ContentValues values = new ContentValues();
        final SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFERENCES_NAME,
                Context.MODE_PRIVATE).edit();
        final ContentResolver resolver = getContentResolver();
        values.put(Filters.Users.TEXT, screen_name);
        resolver.delete(uri, Filters.Users.TEXT + " = '" + screen_name + "'", null);
        resolver.insert(uri, values);
        editor.putBoolean(PREFERENCE_KEY_ENABLE_FILTER, true).commit();
        Toast.makeText(getActivity(), R.string.user_muted, Toast.LENGTH_SHORT).show();
        break;
    }
    case MENU_MENTION: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        final String name = mUser.getName();
        final String screen_name = mUser.getScreenName();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, mAccountId);
        bundle.putString(INTENT_KEY_TEXT, "@" + screen_name + " ");
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, name);
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_SEND_DIRECT_MESSAGE: {
        final Uri.Builder builder = new Uri.Builder();
        builder.scheme(SCHEME_TWEETINGS);
        builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION);
        builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(mAccountId));
        builder.appendQueryParameter(QUERY_PARAM_CONVERSATION_ID, String.valueOf(mUser.getId()));
        startActivity(new Intent(Intent.ACTION_VIEW, builder.build()));
        break;
    }
    case MENU_VIEW_ON_TWITTER: {
        Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                Uri.parse("http://twitter.com/" + mUser.getScreenName()));
        startActivity(browserIntent);
        break;
    }
    case MENU_WANT_RETWEETS: {
        updateFriendship();
        break;
    }
    case MENU_EXTENSIONS: {
        final Intent intent = new Intent(INTENT_ACTION_EXTENSION_OPEN_USER);
        final Bundle extras = new Bundle();
        extras.putParcelable(INTENT_KEY_USER, new ParcelableUser(mUser, mAccountId));
        intent.putExtras(extras);
        startActivity(Intent.createChooser(intent, getString(R.string.open_with_extensions)));
        break;
    }
    case MENU_SET_COLOR: {
        final Intent intent = new Intent(INTENT_ACTION_SET_COLOR);
        startActivityForResult(intent, REQUEST_SET_COLOR);
        break;
    }
    case MENU_CLEAR_COLOR: {
        clearUserColor(getActivity(), mUserId);
        updateUserColor();
        break;
    }
    }
    return true;
}

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

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    final AsyncTwitterWrapper twitter = getTwitterWrapper();
    final ParcelableUser user = getUser();
    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);
            }//from  ww w  . ja va2  s .co  m
        }
        break;
    }
    case MENU_REPORT_SPAM: {
        ReportSpamDialogFragment.show(getFragmentManager(), user);
        break;
    }
    case MENU_ADD_TO_FILTER: {
        final boolean filtering = Utils.isFilteringUser(getActivity(), user.id);
        final ContentResolver cr = getContentResolver();
        if (filtering) {
            final Expression where = Expression.equals(Filters.Users.USER_ID, user.id);
            cr.delete(Filters.Users.CONTENT_URI, where.getSQL(), null);
            Utils.showInfoMessage(getActivity(), R.string.message_user_unmuted, false);
        } else {
            cr.insert(Filters.Users.CONTENT_URI, ContentValuesCreator.createFilteredUser(user));
            Utils.showInfoMessage(getActivity(), R.string.message_user_muted, false);
        }
        break;
    }
    case MENU_MUTE_USER: {
        if (mRelationship != null) {
            if (mRelationship.isSourceMutingTarget()) {
                twitter.destroyMuteAsync(user.account_id, user.id);
            } else {
                CreateUserMuteDialogFragment.show(getFragmentManager(), user);
            }
        }
        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_USER_ID, String.valueOf(user.id));
        final Intent intent = new Intent(Intent.ACTION_VIEW, builder.build());
        intent.putExtra(EXTRA_ACCOUNT, ParcelableCredentials.getAccount(getActivity(), user.account_id));
        intent.putExtra(EXTRA_USER, user);
        startActivity(intent);
        break;
    }
    case MENU_SET_COLOR: {
        final Intent intent = new Intent(getActivity(), ColorPickerDialogActivity.class);
        intent.putExtra(EXTRA_COLOR, mUserColorNameManager.getUserColor(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: {
        final UserColorNameManager manager = UserColorNameManager.getInstance(getActivity());
        manager.clearUserNickname(user.id);
        break;
    }
    case MENU_SET_NICKNAME: {
        final String nick = mUserColorNameManager.getUserNickname(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, Utils.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_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;
    }
    case MENU_ENABLE_RETWEETS: {
        final boolean newState = !item.isChecked();
        final FriendshipUpdate update = new FriendshipUpdate();
        update.retweets(newState);
        twitter.updateFriendship(user.account_id, user.id, update);
        item.setChecked(newState);
        return true;
    }
    case R.id.muted_users: {
        Utils.openMutesUsers(getActivity(), user.account_id);
        return true;
    }
    case R.id.blocked_users: {
        Utils.openUserBlocks(getActivity(), user.account_id);
        return true;
    }
    case R.id.incoming_friendships: {
        Utils.openIncomingFriendships(getActivity(), user.account_id);
        return true;
    }
    case R.id.user_mentions: {
        Utils.openUserMentions(getActivity(), user.account_id, user.screen_name);
        return true;
    }
    case R.id.saved_searches: {
        Utils.openSavedSearches(getActivity(), user.account_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:com.owncloud.android.datamodel.FileDataStorageManager.java

public void deleteFileInMediaScan(String path) {

    String mimetypeString = FileStorageUtils.getMimeTypeFromName(path);
    ContentResolver contentResolver = getContentResolver();

    if (contentResolver != null) {
        if (mimetypeString.startsWith("image/")) {
            // Images
            contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    MediaStore.Images.Media.DATA + "=?", new String[] { path });
        } else if (mimetypeString.startsWith("audio/")) {
            // Audio
            contentResolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    MediaStore.Audio.Media.DATA + "=?", new String[] { path });
        } else if (mimetypeString.startsWith("video/")) {
            // Video
            contentResolver.delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                    MediaStore.Video.Media.DATA + "=?", new String[] { path });
        }//from w  ww.j a va  2s .  co  m
    } else {
        ContentProviderClient contentProviderClient = getContentProviderClient();
        try {
            if (mimetypeString.startsWith("image/")) {
                // Images
                contentProviderClient.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        MediaStore.Images.Media.DATA + "=?", new String[] { path });
            } else if (mimetypeString.startsWith("audio/")) {
                // Audio
                contentProviderClient.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        MediaStore.Audio.Media.DATA + "=?", new String[] { path });
            } else if (mimetypeString.startsWith("video/")) {
                // Video
                contentProviderClient.delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                        MediaStore.Video.Media.DATA + "=?", new String[] { path });
            }
        } catch (RemoteException e) {
            Log_OC.e(TAG, "Exception deleting media file in MediaStore " + e.getMessage());
        }
    }

}

From source file:com.android.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>/* w ww.jav a 2s. co  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 = Sets.newHashSet(mDownloads.keySet());
    final ContentResolver resolver = getContentResolver();
    Cursor cursor = null;
    try {
        cursor = resolver.query(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, null, null, null, null);
        final DownloadInfo.Reader reader = new DownloadInfo.Reader(resolver, cursor);
        final int idColumn = cursor.getColumnIndexOrThrow(Downloads.Impl._ID);
        while (cursor.moveToNext()) {
            final long id = cursor.getLong(idColumn);
            long currentDownloadNextActionMillis = Long.MAX_VALUE;

            DownloadInfo info = mDownloads.get(id);
            if (info != null) {
                updateDownload(reader, info, now);
            } else {
                // Check xunlei engine status when create a new task
                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);
                }

                // if download has been completed, delete xxx, else delete xxx.midownload
                if (info.mStatus == Downloads.Impl.STATUS_SUCCESS) {
                    if (info.mFileName != null) {
                        deleteFileIfExists(info.mFileName);
                    }
                } else {
                    if (info.mFileName != null) {
                        deleteFileIfExists(info.mFileName + Helpers.sDownloadingExtension);
                    }
                }
                resolver.delete(info.getAllDownloadsUri(), null, null);
            } else {
                staleIds.remove(id);
                // Kick off download task if ready
                String pkg = TextUtils.isEmpty(info.mPackage) ? sUnknownPackage : info.mPackage;
                final boolean activeDownload = info.startDownloadIfReady(MyExecutor.getExecutorInstance(pkg));

                // Kick off media scan if completed
                final boolean activeScan = info.startScanIfReady(mScanner);

                // get current download task's next action millis
                currentDownloadNextActionMillis = info.nextActionMillis(now);

                XLConfig.LOGD("Download " + info.mId + ": activeDownload=" + activeDownload + ", activeScan="
                        + activeScan);

                isActive |= activeDownload;
                isActive |= activeScan;
                // if equals 0, keep download service on.
                isActive |= (currentDownloadNextActionMillis == 0);
            }

            // Keep track of nearest next action
            nextActionMillis = Math.min(currentDownloadNextActionMillis, nextActionMillis);
        }
    } catch (SQLiteDiskIOException e) {
        XLConfig.LOGD("error when updateLocked: ", e);
    } catch (Exception e) {
        XLConfig.LOGD("error when updateLocked: ", e);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Clean up stale downloads that disappeared
    for (Long id : staleIds) {
        deleteDownloadLocked(id);
    }

    // Update notifications visible to user
    mNotifier.updateWith(mDownloads.values());

    // 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) {
        XLConfig.LOGD("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.cttapp.bby.mytlc.layer8apps.CalendarHandler.java

private ArrayList<Shift> checkForDuplicates(ArrayList<Shift> newShifts) {
    Preferences pf = new Preferences(this);
    ArrayList<String> oldShifts = pf.getSavedShifts();

    ContentResolver cr = getContentResolver();

    for (String id : oldShifts) {
        Cursor cursor = cr.query(getEventsUri(), new String[] { "dtstart", "dtend" },
                "CALENDAR_ID = " + calID + " AND _ID = " + id, null, null);

        if (!cursor.moveToFirst()) {
            continue;
        }/*from w w w  .  j ava2  s .  c o  m*/

        do {
            Calendar now = Calendar.getInstance();

            Calendar startTime = Calendar.getInstance();
            startTime.setTimeInMillis(cursor.getLong(0));

            Calendar endTime = Calendar.getInstance();
            endTime.setTimeInMillis(cursor.getLong(1));

            if (endTime.compareTo(now) == -1) {
                deleteShift(id);
                continue;
            }

            boolean shiftFound = false;

            for (Shift shift : newShifts) {
                if (shift.getStartDate().get(Calendar.HOUR_OF_DAY) == startTime.get(Calendar.HOUR_OF_DAY)
                        && shift.getEndDate().get(Calendar.MINUTE) == shift.getEndDate().get(Calendar.MINUTE)) {
                    newShifts.remove(shift);
                    shiftFound = true;
                    break;
                }
            }

            if (!shiftFound) {
                cr.delete(getEventsUri(), "CALENDAR_ID = " + calID + " AND _ID = " + String.valueOf(id), null);
            }
        } while (cursor.moveToNext());
    }
    return newShifts;
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Check that an Exception is thrown when unsupported operations are performed
 *//* w w  w  .  j av a 2s .  co m*/
public void testUnsupportedOperations() {
    final ContentResolver cr = getContext().getContentResolver();
    ContentValues dummyValues = new ContentValues();
    Uri[] updateUris = {
            // Can't update most tables in bulk -- only via ID
            FlashCardsContract.Note.CONTENT_URI, FlashCardsContract.Model.CONTENT_URI,
            FlashCardsContract.Deck.CONTENT_ALL_URI,
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").appendPath("cards").build(), };
    for (Uri uri : updateUris) {
        try {
            cr.update(uri, dummyValues, null, null);
            fail("Update on " + uri + " was supposed to throw exception");
        } catch (UnsupportedOperationException e) {
            // This was expected ...
        } catch (IllegalArgumentException e) {
            // ... or this.
        }
    }
    Uri[] deleteUris = { FlashCardsContract.Note.CONTENT_URI,
            // Only note/<id> is supported
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").appendPath("cards").build(),
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").appendPath("cards")
                    .appendPath("2345").build(),
            FlashCardsContract.Model.CONTENT_URI,
            FlashCardsContract.Model.CONTENT_URI.buildUpon().appendPath("1234").build(), };
    for (Uri uri : deleteUris) {
        try {
            cr.delete(uri, null, null);
            fail("Delete on " + uri + " was supposed to throw exception");
        } catch (UnsupportedOperationException e) {
            // This was expected
        }
    }
    Uri[] insertUris = {
            // Can't do an insert with specific ID on the following tables
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").build(),
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").appendPath("cards").build(),
            FlashCardsContract.Note.CONTENT_URI.buildUpon().appendPath("1234").appendPath("cards")
                    .appendPath("2345").build(),
            FlashCardsContract.Model.CONTENT_URI.buildUpon().appendPath("1234").build(), };
    for (Uri uri : insertUris) {
        try {
            cr.insert(uri, dummyValues);
            fail("Insert on " + uri + " was supposed to throw exception");
        } catch (UnsupportedOperationException e) {
            // This was expected ...
        } catch (IllegalArgumentException e) {
            // ... or this.
        }
    }
}

From source file:piuk.blockchain.android.ui.EditAddressBookEntryFragment.java

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
    final WalletApplication application = (WalletApplication) getActivity().getApplication();

    MyRemoteWallet wallet = application.getRemoteWallet();

    this.address = getArguments().getString(KEY_ADDRESS);

    final FragmentActivity activity = getActivity();
    final LayoutInflater inflater = LayoutInflater.from(activity);

    final ContentResolver contentResolver = activity.getContentResolver();
    final Uri uri = AddressBookProvider.CONTENT_URI.buildUpon().appendPath(address).build();

    final String label = AddressBookProvider.resolveLabel(contentResolver, address);

    boolean isAdd = label == null;

    boolean showDelete = !isAdd;

    if (showDelete && wallet != null)
        showDelete = !wallet.isAddressMine(address);

    final Builder dialog = new AlertDialog.Builder(activity)
            .setTitle(isAdd ? R.string.edit_address_book_entry_dialog_title_add
                    : R.string.edit_address_book_entry_dialog_title_edit);

    final View view = inflater.inflate(R.layout.edit_address_book_entry_dialog, null);

    final TextView viewAddress = (TextView) view.findViewById(R.id.edit_address_book_entry_address);
    viewAddress.setText(address.toString());

    final TextView viewLabel = (TextView) view.findViewById(R.id.edit_address_book_entry_label);
    viewLabel.setText(label);/*from  w w w  . j  av a 2 s  .  c o m*/

    dialog.setView(view);

    dialog.setPositiveButton(
            isAdd ? R.string.edit_address_book_entry_dialog_button_add
                    : R.string.edit_address_book_entry_dialog_button_edit,
            new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int whichButton) {
                    AddressBookProvider.setLabel(contentResolver, address, viewLabel.getText().toString());

                    application.setAddressLabel(address, viewLabel.getText().toString());

                    dismiss();
                }
            });

    if (showDelete) {
        dialog.setNeutralButton(R.string.edit_address_book_entry_dialog_button_delete,
                new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int whichButton) {
                        contentResolver.delete(uri, null, null);
                        dismiss();
                    }
                });
    }
    dialog.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialog, final int whichButton) {
            dismiss();
        }
    });

    return dialog.create();
}

From source file:org.zywx.wbpalmstar.plugin.uexcontacts.PFConcactMan.java

public static boolean deletes(final Context context, String inName) {
    ContentResolver cr = context.getContentResolver();
    try {//from   w  ww  . j av  a  2s .c om
        ContentResolver contentResolver = context.getContentResolver();
        if (inName != null) {
            SearchOptionVO searchOptionVO = new SearchOptionVO(500, "", inName, false, false, false, false,
                    false, false, false);
            JSONArray jsonsArray = search(context, searchOptionVO);
            if (jsonsArray != null && jsonsArray.length() > 0) {
                int length = jsonsArray.length();
                boolean hasName = false;
                for (int i = 0; i < length; i++) {
                    JSONObject item = jsonsArray.getJSONObject(i);
                    if (inName.equals(item.getString(EUExCallback.F_JK_NAME))) {
                        hasName = true;
                        break;
                    }
                }
                if (!hasName) {
                    ToastShow(context, finder.getString(context, "plugin_contact_delete_fail"));
                    return false;
                }
                int sdkVersion = Build.VERSION.SDK_INT;
                if (sdkVersion <= 8) {// ?2.2
                    Cursor cur = cr.query(android.provider.Contacts.People.CONTENT_URI, null, null, null, null);
                    cur.moveToFirst();
                    while (cur.moveToNext()) {
                        String name = cur
                                .getString(cur.getColumnIndex(android.provider.Contacts.People.DISPLAY_NAME));
                        String contactName = name;// ??
                        if (contactName != null && contactName.indexOf(" ") != -1) {// 
                            contactName = contactName.replaceAll(" ", "");
                        }
                        if (name != null && contactName.equals(inName)) {
                            contentResolver.delete(android.provider.Contacts.People.CONTENT_URI,
                                    android.provider.Contacts.People.NAME + "=?", new String[] { name });
                        }
                    }
                    cur.close();
                } else if (sdkVersion < 14) {// ?4.0
                    Cursor cur = cr.query(android.provider.ContactsContract.RawContacts.CONTENT_URI, null, null,
                            null, null);
                    cur.moveToFirst();
                    String[] idName = cur.getColumnNames();
                    while (cur.moveToNext()) {
                        String name = cur.getString(
                                cur.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME));
                        String contactId = cur
                                .getString(cur.getColumnIndex(android.provider.ContactsContract.Contacts._ID));
                        String contactName = name;// ??
                        if (contactName != null && contactName.indexOf(" ") != -1) {// 
                            contactName = contactName.replaceAll(" ", "");
                        }
                        if (name != null && contactName.equals(inName)) {
                            contentResolver.delete(android.content.ContentUris.withAppendedId(
                                    android.provider.ContactsContract.Contacts.CONTENT_URI,
                                    Long.parseLong(contactId)), null, null);
                        }
                    }
                    cur.close();
                } else {
                    Cursor cur = cr.query(android.provider.ContactsContract.Contacts.CONTENT_URI, null, null,
                            null, null);
                    while (cur.moveToNext()) {
                        String name = cur.getString(
                                cur.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME));
                        String id = cur
                                .getString(cur.getColumnIndex(android.provider.ContactsContract.Contacts._ID));
                        String contactName = name;// ??
                        if (contactName != null && contactName.indexOf(" ") != -1) {// 
                            contactName = contactName.replaceAll(" ", "");
                        }
                        if (name != null && contactName.equals(inName)) {
                            contentResolver.delete(android.content.ContentUris.withAppendedId(
                                    android.provider.ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id)),
                                    null, null);
                            break;
                        }
                    }
                    cur.close();
                }
                ToastShow(context, finder.getString(context, "plugin_contact_delete_succeed"));
            } else {
                ToastShow(context, finder.getString(context, "plugin_contact_delete_fail"));
                return false;
            }
        }
    } catch (Exception e) {
        ToastShow(context, finder.getString(context, "plugin_contact_delete_fail"));
        return false;
    }
    return true;
}

From source file:org.mariotaku.twidere.fragment.UserFragment.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    final Context context = getContext();
    final AsyncTwitterWrapper twitter = mTwitterWrapper;
    final ParcelableUser user = getUser();
    final UserRelationship userRelationship = mRelationship;
    if (user == null || twitter == null)
        return false;
    switch (item.getItemId()) {
    case R.id.block: {
        if (userRelationship == null)
            return true;
        if (userRelationship.blocking) {
            twitter.destroyBlockAsync(user.account_key, user.key);
        } else {//from www  .j av a2 s.  c  o m
            CreateUserBlockDialogFragment.show(getFragmentManager(), user);
        }
        break;
    }
    case R.id.report_spam: {
        ReportSpamDialogFragment.show(getFragmentManager(), user);
        break;
    }
    case R.id.add_to_filter: {
        if (userRelationship == null)
            return true;
        final ContentResolver cr = getContentResolver();
        if (userRelationship.filtering) {
            final String where = Expression.equalsArgs(Filters.Users.USER_KEY).getSQL();
            final String[] whereArgs = { user.key.toString() };
            cr.delete(Filters.Users.CONTENT_URI, where, whereArgs);
            Utils.showInfoMessage(getActivity(), R.string.message_user_unmuted, false);
        } else {
            cr.insert(Filters.Users.CONTENT_URI, ContentValuesCreator.createFilteredUser(user));
            Utils.showInfoMessage(getActivity(), R.string.message_user_muted, false);
        }
        getFriendship();
        break;
    }
    case R.id.mute_user: {
        if (userRelationship == null)
            return true;
        if (userRelationship.muting) {
            twitter.destroyMuteAsync(user.account_key, user.key);
        } else {
            CreateUserMuteDialogFragment.show(getFragmentManager(), user);
        }
        break;
    }
    case R.id.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 R.id.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_KEY, user.account_key.toString());
        builder.appendQueryParameter(QUERY_PARAM_USER_KEY, user.key.toString());
        final Intent intent = new Intent(Intent.ACTION_VIEW, builder.build());
        intent.putExtra(EXTRA_ACCOUNT,
                ParcelableCredentialsUtils.getCredentials(getActivity(), user.account_key));
        intent.putExtra(EXTRA_USER, user);
        startActivity(intent);
        break;
    }
    case R.id.set_color: {
        final Intent intent = new Intent(getActivity(), ColorPickerDialogActivity.class);
        intent.putExtra(EXTRA_COLOR, mUserColorNameManager.getUserColor(user.key));
        intent.putExtra(EXTRA_ALPHA_SLIDER, false);
        intent.putExtra(EXTRA_CLEAR_BUTTON, true);
        startActivityForResult(intent, REQUEST_SET_COLOR);
        break;
    }
    case R.id.clear_nickname: {
        mUserColorNameManager.clearUserNickname(user.key);
        break;
    }
    case R.id.set_nickname: {
        final String nick = mUserColorNameManager.getUserNickname(user.key);
        SetUserNicknameDialogFragment.show(getFragmentManager(), user.key, nick);
        break;
    }
    case R.id.add_to_list: {
        final Intent intent = new Intent(INTENT_ACTION_SELECT_USER_LIST);
        intent.setClass(getActivity(), UserListSelectorActivity.class);
        intent.putExtra(EXTRA_ACCOUNT_KEY, user.account_key);
        intent.putExtra(EXTRA_SCREEN_NAME,
                DataStoreUtils.getAccountScreenName(getActivity(), user.account_key));
        startActivityForResult(intent, REQUEST_ADD_TO_LIST);
        break;
    }
    case R.id.open_with_account: {
        final Intent intent = new Intent(INTENT_ACTION_SELECT_ACCOUNT);
        intent.setClass(getActivity(), AccountSelectorActivity.class);
        intent.putExtra(EXTRA_SINGLE_SELECTION, true);
        intent.putExtra(EXTRA_ACCOUNT_HOST, user.key.getHost());
        startActivityForResult(intent, REQUEST_SELECT_ACCOUNT);
        break;
    }
    case R.id.follow: {
        if (userRelationship == null)
            return true;
        final boolean updatingRelationship = twitter.isUpdatingRelationship(user.account_key, user.key);
        if (!updatingRelationship) {
            if (userRelationship.following) {
                DestroyFriendshipDialogFragment.show(getFragmentManager(), user);
            } else {
                twitter.createFriendshipAsync(user.account_key, user.key);
            }
        }
        return true;
    }
    case R.id.enable_retweets: {
        final boolean newState = !item.isChecked();
        final FriendshipUpdate update = new FriendshipUpdate();
        update.retweets(newState);
        twitter.updateFriendship(user.account_key, user.key.getId(), update);
        item.setChecked(newState);
        return true;
    }
    case R.id.muted_users: {
        IntentUtils.openMutesUsers(getActivity(), user.account_key);
        return true;
    }
    case R.id.blocked_users: {
        IntentUtils.openUserBlocks(getActivity(), user.account_key);
        return true;
    }
    case R.id.incoming_friendships: {
        IntentUtils.openIncomingFriendships(getActivity(), user.account_key);
        return true;
    }
    case R.id.user_mentions: {
        IntentUtils.openUserMentions(context, user.account_key, user.screen_name);
        return true;
    }
    case R.id.saved_searches: {
        IntentUtils.openSavedSearches(context, user.account_key);
        return true;
    }
    case R.id.scheduled_statuses: {
        IntentUtils.openScheduledStatuses(context, user.account_key);
        return true;
    }
    case R.id.open_in_browser: {
        final Uri uri = LinkCreator.getUserWebLink(user);
        final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setPackage(IntentUtils.getDefaultBrowserPackage(context, uri, true));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            startActivity(intent);
        }
        return true;
    }
    default: {
        final Intent intent = item.getIntent();
        if (intent != null && intent.resolveActivity(context.getPackageManager()) != null) {
            startActivity(intent);
        }
        break;
    }
    }
    return true;
}