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.ohmage.db.DbHelper.java

/**
 * Removes survey responses that are "stale" for the given campaignUrn.
 * //from w  ww.ja  v  a  2s.  co m
 * Staleness is defined as a survey response whose source field is "remote",
 * or a response whose source field is "local" and uploaded field is 1.
 * 
 * @return
 */
public int removeStaleResponseRows(String campaignUrn) {
    // build and execute the delete on the response table
    String whereClause = "(" + Responses.RESPONSE_STATUS + "=" + Response.STATUS_DOWNLOADED + " or "
            + Responses.RESPONSE_STATUS + "=" + Response.STATUS_UPLOADED + ")";

    if (campaignUrn != null)
        whereClause += " and " + Responses.CAMPAIGN_URN + "='" + campaignUrn + "'";

    // get a contentresolver and pass the delete onto it (so it can notify,
    // etc.)
    ContentResolver cr = mContext.getContentResolver();
    return cr.delete(Responses.CONTENT_URI, whereClause, null);
}

From source file:p1.nd.khan.jubair.mohammadd.popularmovies.adapter.MovieDetailsAdapter.java

/**
 * Method to check if movie is favorite.
 *
 * @param movieId to check.//from   www . j a  va  2  s .com
 * @return true if movie is deleted
 */
private int deleteFromFavorites(int movieId) {
    String[] projection = new String[] { "*" };
    String selection = MovieEntry.C_MOVIE_ID + "=?";
    String[] selectionArgs = { String.valueOf(movieId) };

    ContentResolver contentResolver = mContext.getContentResolver();
    Cursor cMovies = null;
    Cursor cTrailers = null;
    Cursor cReviews = null;
    int result = 0;

    try {
        cMovies = contentResolver.query(MovieEntry.FAVORITES_CONTENT_URI, projection, selection, selectionArgs,
                null);
        if (null != cMovies && cMovies.moveToFirst()) {
            result = contentResolver.delete(MovieEntry.FAVORITES_CONTENT_URI, selection, selectionArgs);
        }
        cTrailers = contentResolver.query(TrailersEntry.FAVORITES_CONTENT_URI, projection, selection,
                selectionArgs, null);
        while (null != cTrailers && cTrailers.moveToNext()) {
            result = contentResolver.delete(TrailersEntry.FAVORITES_CONTENT_URI, selection, selectionArgs);
        }
        cReviews = contentResolver.query(ReviewsEntry.FAVORITES_CONTENT_URI, projection, selection,
                selectionArgs, null);
        while (null != cReviews && cReviews.moveToNext()) {
            result = contentResolver.delete(ReviewsEntry.FAVORITES_CONTENT_URI, selection, selectionArgs);
        }
    } finally {
        if (null != cMovies)
            cMovies.close();
        if (null != cTrailers)
            cTrailers.close();
        if (null != cReviews)
            cReviews.close();
    }
    return result;
}

From source file:ca.ualberta.cmput301w14t08.geochan.fragments.ExpandImageFragment.java

/**
 * Initializes the UI of the fragment./*from  w ww . ja v  a 2 s.c om*/
 */
@Override
public void onStart() {
    super.onStart();
    ProgressDialog dialog = new ProgressDialog(getActivity());
    dialog.setMessage("Downloading Image");
    ImageView imageView = (ImageView) getView().findViewById(R.id.expanded_image);
    final Bitmap image = CacheManager.getInstance().deserializeImage(id);
    if (image == null) {
        // Start the image getter thread.
        ThreadManager.startGetImage(id, imageView, dialog);
    } else {
        imageView.setImageBitmap(image);
        ThreadManager.startGetImage(id, imageView, null);
    }
    LinearLayout rlayout = (LinearLayout) getView().findViewById(R.id.expanded_image_relative);
    rlayout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().popBackStack();
        }
    });
    Button saveButton = (Button) getView().findViewById(R.id.save_image_button);
    saveButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            ContentValues values = new ContentValues();
            values.put(Images.Media.TITLE, id);
            values.put(Images.Media.DESCRIPTION, id);
            values.put(Images.Media.MIME_TYPE, "image/jpeg");
            values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());

            Uri uri = null;
            ContentResolver contentResolver = getActivity().getContentResolver();
            try {
                uri = contentResolver.insert(Images.Media.EXTERNAL_CONTENT_URI, values);
                OutputStream imageOut = contentResolver.openOutputStream(uri);
                try {
                    image.compress(Bitmap.CompressFormat.JPEG, 90, imageOut);
                } finally {
                    imageOut.close();
                }
                Toast.makeText(getActivity(), "Saved to gallery.", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toaster.toastShort("Failed to save to gallery.");
                if (uri != null) {
                    contentResolver.delete(uri, null, null);
                    uri = null;
                }
            }
        }
    });
}

From source file:com.stockita.stockitapointofsales.salespack.pendingpack.SalesPendingListFragmentUI.java

/**
 * This method will insert the current Sales Detail Pending into a local database
 * so later can be query by {@link SalesPendingCheckoutDialogFragment}
 *//*from  w w  w .jav a 2  s  . c o  m*/
private void packTheCurrentSalesDetailPendingInToLocalDatabase() {

    // Delete all data in the local database before we insert new data
    final ContentResolver contentResolver = getActivity().getContentResolver();
    contentResolver.delete(ContractData.SalesDetailPendingEntry.CONTENT_URI, null, null);

    // Get the reference to ../SalesDetailPending/...
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(mUserUid)
            .child(Constants.FIREBASE_SALES_DETAIL_PENDING_LOCATION);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (!dataSnapshot.hasChildren()) {
                return;
            }

            // Iterate
            for (DataSnapshot snap : dataSnapshot.getChildren()) {

                // Initialize the content values
                ContentValues values = new ContentValues();

                // Initialize the model
                SalesDetailModel model = snap.getValue(SalesDetailModel.class);

                // Get the state
                String key = snap.getKey();
                String itemNumber = model.getItemNumber();
                String itemDesc = model.getItemDesc();
                String itemUnit = model.getItemUnit();
                String itemPrice = model.getItemPrice();
                String itemQty = model.getItemQuantity();
                String itemDiscount = model.getItemDiscount();
                String itemDiscountAmount = model.getItemDiscountAmout();
                String itemAmount = model.getItemAmount();

                // Pack into ContentValues object
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_PUSH_KEY, key);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_NUMBER, itemNumber);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DESC, itemDesc);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_UNIT, itemUnit);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_PRICE, itemPrice);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_QUANTITY, itemQty);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT, itemDiscount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT_AMOUNT,
                        itemDiscountAmount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_AMOUNT, itemAmount);

                // Insert into local database
                try {
                    contentResolver.insert(ContractData.SalesDetailPendingEntry.CONTENT_URI, values);
                } catch (Exception e) {
                    Log.e(TAG_LOG, e.getMessage());
                }
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.e(TAG_LOG, databaseError.getMessage());
        }
    });

}

From source file:com.chatwing.whitelabel.managers.ChatboxModeManager.java

private void markNotificationRead(int chatBoxId) {
    Uri uri = ChatWingContentProvider.getNotificationMessagesUri();

    ContentResolver contentResolver = mActivityDelegate.getActivity().getContentResolver();
    contentResolver.delete(uri, NotificationMessagesTable.CHAT_BOX_ID + "==" + chatBoxId, null);
}

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

@Override
public boolean onMenuItemClick(final MenuItem item) {
    final ParcelableStatus status = mSelectedStatus;
    if (status == null)
        return false;
    final long account_id = getDefaultAccountId(mApplication);
    switch (item.getItemId()) {
    case MENU_VIEW: {
        openStatus(getActivity(), status);
        break;/*  www  . ja v a2s  .  c o m*/
    }
    case MENU_SHARE: {
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "@" + status.screen_name + ": " + status.text_plain);
        startActivity(Intent.createChooser(intent, getString(R.string.share)));
        break;
    }
    case MENU_TRANSLATE: {
        translate(status);
        break;
    }
    case MENU_RETWEET: {
        if (isMyRetweet(status)) {
            mService.destroyStatus(status.account_id, status.status_id);
        } else {
            final long id_to_retweet = mSelectedStatus.is_retweet && mSelectedStatus.retweet_id > 0
                    ? mSelectedStatus.retweet_id
                    : mSelectedStatus.status_id;
            mService.retweetStatus(status.account_id, id_to_retweet);
        }
        break;
    }
    case MENU_QUOTE: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putBoolean(INTENT_KEY_IS_QUOTE, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), status.screen_name, status.text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_QUOTE_REPLY: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putLong(INTENT_KEY_IN_REPLY_TO_ID, status.status_id);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, status.screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, status.name);
        bundle.putBoolean(INTENT_KEY_IS_QUOTE, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), status.screen_name, status.text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_ADD_TO_BUFFER: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putBoolean(INTENT_KEY_IS_BUFFER, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), status.screen_name, status.text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_REPLY: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        final List<String> mentions = new Extractor().extractMentionedScreennames(status.text_plain);
        mentions.remove(status.screen_name);
        mentions.add(0, status.screen_name);
        bundle.putStringArray(INTENT_KEY_MENTIONS, mentions.toArray(new String[mentions.size()]));
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putLong(INTENT_KEY_IN_REPLY_TO_ID, status.status_id);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_TWEET, status.text_plain);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, status.screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, status.name);
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_FAV: {
        if (mSelectedStatus.is_favorite) {
            mService.destroyFavorite(status.account_id, status.status_id);
        } else {
            mService.createFavorite(status.account_id, status.status_id);
        }
        break;
    }
    case MENU_CONVERSATION: {
        openConversation(getActivity(), status.account_id, status.status_id);
        break;
    }
    case MENU_DELETE: {
        mService.destroyStatus(status.account_id, status.status_id);
        break;
    }
    case MENU_EXTENSIONS: {
        final Intent intent = new Intent(INTENT_ACTION_EXTENSION_OPEN_STATUS);
        final Bundle extras = new Bundle();
        extras.putParcelable(INTENT_KEY_STATUS, status);
        intent.putExtras(extras);
        startActivity(Intent.createChooser(intent, getString(R.string.open_with_extensions)));
        break;
    }
    case MENU_MULTI_SELECT: {
        if (!mApplication.isMultiSelectActive()) {
            mApplication.startMultiSelect();
        }
        final NoDuplicatesLinkedList<Object> list = mApplication.getSelectedItems();
        if (!list.contains(status)) {
            list.add(status);
        }
        break;
    }
    case MENU_BLOCK: {
        mService.createBlock(account_id, status.user_id);
        break;
    }
    case MENU_REPORT_SPAM: {
        mService.reportSpam(account_id, status.user_id);
        break;
    }
    case MENU_MUTE_USER: {
        final String screen_name = status.screen_name;
        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_MAKE_GAP: {
        Uri uri = Statuses.CONTENT_URI;
        final Uri query_uri = buildQueryUri(uri, false);
        ContentResolver mResolver = getContentResolver();
        final ContentValues values = new ContentValues();
        values.put(Statuses.IS_GAP, 1);
        final StringBuilder where = new StringBuilder();
        where.append(Statuses.ACCOUNT_ID + "=" + account_id);
        where.append(" AND " + Statuses.STATUS_ID + "=" + status.status_id);
        mResolver.update(query_uri, values, where.toString(), null);
        getActivity().sendBroadcast(new Intent(BROADCAST_FILTERS_UPDATED).putExtra(INTENT_KEY_SUCCEED, true));
        break;
    }
    case MENU_COPY: {
        final CharSequence text = Html.fromHtml(status.text_html);
        if (ClipboardUtils.setText(getActivity(), text)) {
            Toast.makeText(getActivity(), R.string.text_copied, Toast.LENGTH_SHORT).show();
        }
        break;
    }
    }
    return true;
}

From source file:com.jefftharris.passwdsafe.sync.MainActivity.java

/** Remove an account */
private void removeAccount(Uri currAcct) {
    new AccountUpdateTask(currAcct, getString(R.string.removing_account)) {
        @Override/* ww  w.j av  a  2  s.co m*/
        protected void doAccountUpdate(ContentResolver cr) {
            if (itsAccountUri != null) {
                cr.delete(itsAccountUri, null, null);
            }
        }
    }.startTask(this, this);
}

From source file:org.getlantern.firetweet.service.BackgroundOperationService.java

private void handleDiscardDraftIntent(Intent intent) {
    final Uri data = intent.getData();
    if (data == null)
        return;/*  ww w . j ava 2 s .c  o  m*/
    mNotificationManager.cancel(data.toString(), NOTIFICATION_ID_DRAFTS);
    final ContentResolver contentResolver = getContentResolver();
    final long id = ParseUtils.parseLong(data.getLastPathSegment(), -1);
    final Expression where = Expression.equals(Drafts._ID, id);
    contentResolver.delete(Drafts.CONTENT_URI, where.getSQL(), null);
}

From source file:com.stockita.stockitapointofsales.salespack.openpack.OpenSalesDetailFragmentUI.java

/**
 * This method will insert the current Sales Detail Open into a local database
 * so later can be query by {@link OpenSalesCheckoutDialogFragment}
 *///  ww w.j a  va2 s . co  m
private void packTheCurrentSalesDetailOpenInToLocalDatabase() {

    // Delete all data in the local database before we insert new data
    final ContentResolver contentResolver = getActivity().getContentResolver();
    contentResolver.delete(ContractData.SalesDetailPendingEntry.CONTENT_URI, null, null);

    // Get the reference to ../openSalesDetail/...
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(mUserUid)
            .child(Constants.FIREBASE_OPEN_SALES_DETAIL_LOCATION).child(mSalesHeaderKey);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            // Iterate
            for (DataSnapshot snap : dataSnapshot.getChildren()) {

                // Initialize the content values
                ContentValues values = new ContentValues();

                // Initialize the model
                SalesDetailModel model = snap.getValue(SalesDetailModel.class);

                // Get the state
                String key = snap.getKey();
                String itemNumber = model.getItemNumber();
                String itemDesc = model.getItemDesc();
                String itemUnit = model.getItemUnit();
                String itemPrice = model.getItemPrice();
                String itemQty = model.getItemQuantity();
                String itemDiscount = model.getItemDiscount();
                String itemDiscountAmount = model.getItemDiscountAmout();
                String itemAmount = model.getItemAmount();

                // Pack into ContentValues object
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_PUSH_KEY, key);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_NUMBER, itemNumber);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DESC, itemDesc);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_UNIT, itemUnit);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_PRICE, itemPrice);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_QUANTITY, itemQty);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT, itemDiscount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT_AMOUNT,
                        itemDiscountAmount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_AMOUNT, itemAmount);

                // Insert into local database
                try {
                    contentResolver.insert(ContractData.SalesDetailPendingEntry.CONTENT_URI, values);
                } catch (Exception e) {
                    Log.e(TAG_LOG, e.getMessage());
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.e(TAG_LOG, databaseError.getMessage());
        }
    });
}

From source file:org.opendatakit.tables.utils.CollectUtil.java

/**
 * Delete the form specified by the id given in the parameters. Does not check
 * form version./*from   w  ww .j ava  2  s.c  o m*/
 *
 * @param resolver
 *          ContentResolver of the calling activity
 * @param formId
 *          the id of the form to be deleted
 * @return the result of the the delete call
 */
private static int deleteForm(ContentResolver resolver, String appName, String formId) {
    try {
        return resolver.delete(CONTENT_FORM_URI, COLLECT_KEY_JR_FORM_ID + "=?", new String[] { formId });
    } catch (Exception e) {
        WebLogger.getLogger(appName).d(TAG,
                "caught an exception while deleting a form, returning 0 and " + "proceeding");
        return 0;
    }
}