How to get row count in sqlite using Android? How to get row count in sqlite using Android? android android

How to get row count in sqlite using Android?


Using DatabaseUtils.queryNumEntries():

public long getProfilesCount() {    SQLiteDatabase db = this.getReadableDatabase();    long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);    db.close();    return count;}

or (more inefficiently)

public int getProfilesCount() {    String countQuery = "SELECT  * FROM " + TABLE_NAME;    SQLiteDatabase db = this.getReadableDatabase();    Cursor cursor = db.rawQuery(countQuery, null);    int count = cursor.getCount();    cursor.close();    return count;}

In Activity:

int profile_counts = db.getProfilesCount();    db.close();


Use android.database.DatabaseUtils to get number of count.

public long getTaskCount(long tasklist_Id) {        return DatabaseUtils.queryNumEntries(readableDatabase, TABLE_NAME);}

It is easy utility that has multiple wrapper methods to achieve database operations.


c.getCount() returns 1 because the cursor contains a single row (the one with the real COUNT(*)). The count you need is the int value of first row in cursor.

public int getTaskCount(long tasklist_Id) {    SQLiteDatabase db = this.getReadableDatabase();    Cursor cursor= db.rawQuery(        "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",         new String[] { String.valueOf(tasklist_Id) }    );    int count = 0;    if(null != cursor)        if(cursor.getCount() > 0){          cursor.moveToFirst();              count = cursor.getInt(0);        }        cursor.close();    }    db.close();    return count;}