Search code examples
androidsqliteandroid-contentprovider

How to delete first "n" rows using content provider


I want to delete first "n" rows using content provider.

This is my code:

    private void deleteOldItems(int number) {
    String where = HistoryTable.COLUMN_ID + "<=?";
    getContentResolver()
            .delete(Uri.parse("content://com.ipiit.client.contentprovider.HistoryContentProvider/histories"),
                    where, new String[] {String.valueOf(number)});
    }

I works but only one time. How to always delete first rows?


Solution

  • If this is your "own" ContentProvider, i.e. you are sure of the table names and similar stuff you can always do a rather ugly subselect like this:

    private void deleteOldItems(int number) {
        // You should probably sort the subselect on something
        // suitable indicating its age. The COLUMN_ID should do.
        String where = HistoryTable.COLUMN_ID + " IN (SELECT " + HistoryTable.COLUMN_ID + " FROM " + 
            HistoryTable.TABLE_NAME + " ORDER BY " + HistoryTable.COLUMN_ID + " LIMIT ?)";
        getContentResolver()
            .delete(Uri.parse("content://com.ipiit.client.contentprovider.HistoryContentProvider/histories"),
                    where, new String[] {String.valueOf(number)});
    }
    

    On the other hand, if it's your own ContentProvider .. just add support for adding a "limit" parameter to the URI when passing it to #delete(..) instead of resorting to ugly hacks like this.