AAA
AAA

Reputation: 37

ContentResolver Delete

I am having trouble trying to delete a row of data with a specific ID, instead of deleting all the data that is in my database through a content provider.

Here is the delete content provider method:

@Override
    public int delete(@NonNull Uri uri, @Nullable String selection,
            @Nullable String[] selectionArgs) {
        switch(sUriMatcher.match(uri))
        {
            case CARD:
                selection = (selection == null) ? "1" : selection;
                break;
            case CARD_WITH_ID:
                long id = ContentUris.parseId(uri);
                selection = String.format("%s = ?", Contract.Columns._ID);
                selectionArgs = new String[]{String.valueOf(id)};
                break;
            default:
                throw new IllegalArgumentException("Illegal delete URI");
        }

        SQLiteDatabase db = mCardSQLite.getWritableDatabase();
        int count = db.delete(Contract.TABLE_NAME, selection, selectionArgs);

        if(count > 0)
        {
            //Notify observers of the change
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

I'm trying to get the CARD_WITH_ID section of the switch statement to run. I can't understand why it is not.

Here is the query I'm trying to test this with

getContentResolver().delete(CardProvider.Contract.CONTENT_URI,CardProvider.Contract.Columns._ID ,null);

How can I select only one column and not all of them like I'm doing in the code above?

Upvotes: 1

Views: 3996

Answers (1)

mahendri
mahendri

Reputation: 81

yes, the URI you provided to .delete() is incorrect. That means the content of uri from sUriMatcher.match(uri) you provide is CardProvider.Contract.CONTENT_URI. That URI is not URI for specific id and of course will match to CARD section

to make .delete() go into CARD_WITH_ID you need to do this:

long id = 1; //id of row that you want to delete
Uri deleteUri = ContentUris.withAppendedId(CardProvider.Contract.CONTENT_URI, id);
//notice code below, not necessary to provide where and selectionArgs as CARD_WITH_ID section wil override it
getContentResolver().delete(uri, null, null);

And make sure to register that URI in sUriMatcher

static {
    ...
    sUriMatcher.addURI(YOUR_CONTENT_AUTHORITY, YOUR_PATH + "/#", CARD_WITH_ID);

Upvotes: 2

Related Questions