How can I limit the number of rows in Android SQLite table

前端 未结 3 1119
既然无缘
既然无缘 2020-12-05 23:57

I create an Android app that has \"recents history\". I would like to limit the size of this table to a maximum of 50 rows (according to their insert date).

I saw se

3条回答
  •  既然无缘
    2020-12-06 00:25

    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 . 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);
        }
    }
    

提交回复
热议问题