Sqlite Count Example
I am using SQLite in Android. I have the query, query executed and how to print count from cursor. Cursor dataCount = mDb.rawQuery('select count(*) from ' + DATABASE_JOURNAL_TABLE,
Solution 1:
You already have the correct approach.
Cursor cursor = database.rawQuery("select count(*) from " + DATABASE_JOURNAL_TABLE, null);
// ensure there is at least one row and one columnif (cursor.getCount() > 0 && cursor.getColumnCount() > 0) {
cursor.close();
return cursor.getInt(0);
} else {
cursor.close();
return0;
}
You must check that there is at least 1 row and 1 column, if you provide a table that does not yet exist there will be no column to access and cursor.getInt(0) will throw an exception.
source: https://github.com/samkirton/SQLKing
Solution 2:
May be by getInt(index) as
cursor.getInt(1); // this is for example, you have to adjust index in your code
Also cursor has a built in function getCount() to return row number so can also do like this:
// assuming your table has `id` column as primary key or unique key.CursordataCount= mDb.rawQuery("select id from " + DATABASE_JOURNAL_TABLE, null);
dataCount.getCount();
See android devloper's doc for Cursor for more information.
Post a Comment for "Sqlite Count Example"