How to get the row count of a query in Android using SQLite?

53,242

Solution 1

Cursor.getCount()

Solution 2

cursor.moveToNext();
cursor.getCount();

If the moveToNext() is not called, the cursorIndexOutOfBoundException may arise.

Solution 3

This would be more efficient because work for all versions:

int numRows = DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM table_name", null);

or

int numRows = DatabaseUtils.queryNumEntries(db, "table_name");

or if you want to get number of rows which specific selection then you should go with (added in API 11)

public static long queryNumEntries (SQLiteDatabase db, String table, String selection)

Thanks :)

Solution 4

use String instead of int

String strCount = "";
int count = 0;
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

Cursor cursor = db.rawQuery(
    "select count(*) from downloadedFragement where mixId=?",
    new String[]{String.valueOf(mixId)});

while(cursor.moveToFirst()){
    strCount = cursor.getString(cursor.getColumnIndex("COUNT(*)"));
}
count = Integer.valueOf(strCount).intValue();
Share:
53,242
David
Author by

David

Updated on July 09, 2022

Comments

  • David
    David almost 2 years

    How do I get the row count of a query in Android using SQLite? It seems my following method does not work.

    public int getFragmentCountByMixId(int mixId) {
        int count = 0;
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
    
        Cursor cursor = db.rawQuery(
            "select count(*) from downloadedFragement where mixId=?",
            new String[]{String.valueOf(mixId)});
        while(cursor.moveToFirst()){
            count = cursor.getInt(0);
        }
        return count;
    }