mardi 18 août 2015

Counting number of records in SQLite table incorrectly returns 0

I am testing my app in Android Studio with a Galaxy Nexus API 18 in the emulator. My app works fine in API 21, but with API 18 I have a problem counting the number of records in a SQLite database.

In my MainActivity I call a method of my DBAdapter class

db = new DBAdapter(this);
db.open();
mCursor = db.get7RandomRecepten();

The code of the method is:

public Cursor get7RandomRecepten() {

    //int numRows = (int) DatabaseUtils.queryNumEntries(db, DATABASE_TABLE);

    String sql = "select count(*) from " + DATABASE_TABLE;
    Cursor mCount= db.rawQuery(sql, null);
    mCount.moveToFirst();
    int numRows= (int) mCount.getInt(0);

    if (numRows == 0) {
        return null;
    } else if (numRows < 7) {
        return  db.query(DATABASE_TABLE + " ORDER BY RANDOM() LIMIT " + numRows, new String[] {KEY_ROWID, KEY_RECEPT_TITEL, KEY_RECEPT_INVOERDATUM}, null, null, null, null, null);
    } else {
        return  db.query(DATABASE_TABLE + " ORDER BY RANDOM() LIMIT 7", new String[] {KEY_ROWID, KEY_RECEPT_TITEL, KEY_RECEPT_INVOERDATUM}, null, null, null, null, null);
    }
}

The method get7RandomRecepten returns null because the count results in 0 (which is not the case).

I also tried with DatabaseUtils.queryNumEntries, but the same result.

Does someone have an idea how to solve this? Thanks!

Aucun commentaire:

Enregistrer un commentaire