lundi 23 novembre 2015

Sqlite query to keep the last 5 searches on android

I have a SQLite database in my android app.

Each time I open the search activity of my app, I want to display a list of my search history but limited to the latest 5 searched items.

DBHelper searchDBHelper = DBHelper.getInstance(getApplicationContext()); //extends SQLiteOpenHelper
//lookup the historical data from the DB first and pass it to the adapter
try {
    searchDBHelper.deletePlaceSearchItems();
    hSearchDao = searchDBHelper.getHSearchDao();
    searchArrayList = new LinkedList<>(hSearchDao.queryForAll());
    historicalSearchAdapter = new HistoricalSearchAdapter(searchArrayList);

} catch (SQLException e) {
    e.printStackTrace();
}

my SearchDBHelper.java has the following delete method in it which is called above:

public void deletePlaceSearchItems() {
    SQLiteDatabase db = getWritableDatabase();
        String[] args ={"5"};
        db.rawQuery("DELETE FROM placesearch " +
                "WHERE id < (" +
                " SELECT MIN(id)" +
                " FROM (SELECT id" +
                " FROM placesearch" +
                " ORDER BY date DESC" +
                " LIMIT ?))", args);
}

The sqlite query code was obtained from here: Keep only N last records in SQLite database, sorted by date

I keep on running the app but the code does not seem to delete anything at all. Also not sure how I can debug this as no error message was printed to my logs. This is what my sqlite db looks like inside - it has 6 items:

sqlite database

What is wrong with my code?

Aucun commentaire:

Enregistrer un commentaire