views:

86

answers:

2

Hi guys,

The following function is giving me an out of bounds exception...

public void count(){
    SQLiteDatabase db = table.getWritableDatabase();
    String count = "SELECT count(*) FROM table";
    Cursor mcursor = db.rawQuery(count, null);
    int icount = mcursor.getInt(0);
    System.out.println("NUMBER IN DB: " + icount);
}

It's meant to return the number of rows in the database. Anybody know whats wrong? am I perhaps doing this task the wrong way?

+5  A: 

You missed out

mcursor.moveToFirst();

public void count(){
    SQLiteDatabase db = table.getWritableDatabase();
    String count = "SELECT count(*) FROM table";
    Cursor mcursor = db.rawQuery(count, null);
    mcursor.moveToFirst();
    int icount = mcursor.getInt(0);
    System.out.println("NUMBER IN DB: " + icount);
}

But you should use better methods for this task, like the inbuilt helpers of DatabaseUtils

such as

public long count() {
    return DatabaseUtils.queryNumEntries(db,'tablename');
}

You might find helpful to use DatabaseUtils.longForQuery() to get the first column long value, when you have where query for the total count. It's simpler and you do not need that bunch of work with the Cursor.

Pentium10
That worked, thanks :)
Ulkmun
Aidan, you should click the "tick" mark if you feel this is the right answer.
J-16 SDiZ
Interesting - I would have expected creating a new Cursor would move it to the first record instead of "before first" - good to know Android adds that concept too (I'm more used to having only an "after last"). Wondering too, what's better, doing this (I would expect so), or `SELECT * FROM table` and then `getCount()` on the resulting cursor?
Joubarc
@J-16 SDiZ You can mark an answer as accepted only after 15 minutes. @Joubarc probably the DatabaseUtils are way more optimized, that the code you do with getCount();
Pentium10
`DatabaseUtils` may possibly be well optimised, but if you've already done the query and have the `Cursor` then I very much doubt calling `getCount()` on it will be any slower.
Christopher
A: 

need to move the cursor to the first (and only) row

Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
JoshP