Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQLite Cursor out of bounds exception on SELECT count(*) FROM table

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?

like image 448
Skizit Avatar asked Jun 22 '10 14:06

Skizit


2 Answers

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.

like image 147
Pentium10 Avatar answered Oct 16 '22 03:10

Pentium10


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

Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
like image 35
JoshP Avatar answered Oct 16 '22 03:10

JoshP