Check out SearchRecentSuggestions
's source code for an example. It has a method to truncate history up to a given number of entries, using LIMIT -1 OFFSET <maxEntries>
. You have to sort the entries by the reversed order of insertion first, then skip the first maxEntries
.
If you call this automatically every upon insertion, then you only need to LIMIT 1
as there can never be more than maxEntries + 1
anyway.
/**
* Reduces the length of the history table, to prevent it from growing too large.
*
* @param cr Convenience copy of the content resolver.
* @param maxEntries Max entries to leave in the table. 0 means remove all entries.
*/
protected void truncateHistory(ContentResolver cr, int maxEntries) {
if (maxEntries < 0) {
throw new IllegalArgumentException();
}
try {
// null means "delete all". otherwise "delete but leave n newest"
String selection = null;
if (maxEntries > 0) {
selection = "_id IN " +
"(SELECT _id FROM suggestions" +
" ORDER BY " + SuggestionColumns.DATE + " DESC" +
" LIMIT -1 OFFSET " + String.valueOf(maxEntries) + ")";
}
cr.delete(mSuggestionsUri, selection, null);
} catch (RuntimeException e) {
Log.e(LOG_TAG, "truncateHistory", e);
}
}