user1602798
user1602798

Reputation: 365

How to count number of records in sqlite in Android

I am working on android project. I used sqlite database for it. I have tables in database. I have created databasehelper class. i want to count number of records in particular table. how can i achieve this ? any help will be appreciated?

Upvotes: 18

Views: 38839

Answers (6)

Neyomal
Neyomal

Reputation: 1649

In db handler class use this method

Kotlin Code :

fun getCount(): Int {
        val db = this.readableDatabase
        var count= db.rawQuery("SELECT * FROM $TABLE_NAME", null).count
        db.close()
        return count
    }

Then directly call getCount after creating an instance of db handler class

Upvotes: 0

Samir
Samir

Reputation: 6605

In Kotlin

fun getFruitTableCount(): Int {
        val db = readableDatabase
        val numRows = DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM " + DBContract.FruitEntry.TABLE_NAME, null).toInt()
        return numRows
    }

Upvotes: 1

Victor USA
Victor USA

Reputation: 1

Please try this:

In your DatabaseHelper.java:

public Cursor getYourTableContents() {
  SQLiteDatabase db = this.getWritableDatabase();

  Cursor data = db.rawQuery("SELECT * FROM " + "Your table name", null);

  return data;
}

To get the number of rows in your table:

Cursor yourCursor = myDB.getYourTableContents();

int i = 0;

while (yourCursor.moveToNext()) {
  i += 1;
}

i is your rows count as an integer.

Upvotes: 0

user370305
user370305

Reputation: 109237

Using SELECT COUNT(*) FROM table_name query and, than count the size of Cursor..

The method from Cursor to count size (number of rows in cursor) is,

getCount()

Returns the numbers of rows in the cursor.

OR:

From DatabaseUtils use method queryNumEntries(SQLiteDatabase db, String table)

Like,

long numberOfRows = DatabaseUtils.queryNumEntries(db, "table_name");

which returns the number of rows in the table.

Upvotes: 17

Nick Bradbury
Nick Bradbury

Reputation: 1745

This would be more efficient:

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

Or:

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

Upvotes: 52

Chirag
Chirag

Reputation: 56925

Try this.

Cursor c = db.rawQuery("select * from your_table_name",null);
Log.i("Number of Records"," :: "+c.getCount());

Edit : c.getCount() returns the number of records of particular table.

Upvotes: 10

Related Questions