lundi 20 juillet 2015

keep DB always with maximum 100 records in SQLite/android

hi there I use this function to insert/delete an record in SQLite android.

// Adding new bookMark

public void addBookMark(BookMark bookMark) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_TITLE, bookMark.getTitle()); // BookMark Name
    values.put(KEY_URL, bookMark.getURL()); // BookMark Phone

    // Inserting Row
    db.insert(TABLE_BOOKMARKS, null, values);
    db.close(); // Closing database connection
}

// Deleting single bookMark

public void deleteBookMark(BookMark bookMark) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_BOOKMARKS, KEY_ID + " = ?",
                new String[] { String.valueOf(bookMark.getID()) });
        db.close();
    }

Now I want keep only last 100 record in DB. (I want check when I insert a new record.if the count was more than 100...The code remove oldest records.

something like this aql code:

DELETE FROM TABLE_BOOKMARKS where KEY_ID NOT IN (SELECT KEY_ID from TABLE_BOOKMARKS ORDER BY KEY_ID DESC LIMIT 100)

I think the top code is true but how can I use it in this code:

// Adding new bookMark and keep 100 record always.

public void addBookMarkAndKeep100(BookMark bookMark) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_TITLE, bookMark.getTitle()); // BookMark TITLE
    values.put(KEY_URL, bookMark.getURL()); // BookMark URL

    // Inserting Row
    db.insert(TABLE_BOOKMARKS, null, values);

    db.delete(?);
    db.close(); // Closing database connection
}

Aucun commentaire:

Enregistrer un commentaire