Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...