mukesh
mukesh

Reputation: 4140

How to count row of a table from sqlite database android

I want to count rows of a table in android.I used 2 ways but not success & get a warning message

Launch timeout has expired, giving up wake lock!
 Activity idle timeout for HistoryRecord{44e26a30 com.india.screen/.CategoryList}

I have tried-

String query="Select count(*) from Holyplace_Tbl";
  1. Using rawQuery

    public void countRows(String query) {

    Cursor mcursor = assetDatabaseHelper.executeQuery(query);
    mcursor.moveToFirst();
    int icount = mcursor.getInt(0);
    System.out.println("NUMBER IN DB: " + icount);
    mcursor.close();
    

    }

  2. Using DatabaseUtils

    public int countRows(String query)
    {
    
       int sometotal = (int) DatabaseUtils.longForQuery(sqliteDatabaseObj, query, null);
      return sometotal;
     }
    

    AssetDatabaseOpenHelper.class

Upvotes: 3

Views: 17651

Answers (5)

Javed Tahasildar
Javed Tahasildar

Reputation: 1

You can get row count as follows:

c = db.rawQuery("SELECT * FROM Your_tabename", null);
int i = c.getCount();

Upvotes: 0

Nitin Karale
Nitin Karale

Reputation: 799

long numRows = DatabaseUtils.queryNumEntries(db, table);

Upvotes: 0

Pratik Butani
Pratik Butani

Reputation: 62419

Simplest and Efficient way that i found from How to count number of records in sqlite

DatabaseUtils provides Static utility methods for dealing with databases and Cursors.

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

Or:

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

Upvotes: 4

Anup Cowkur
Anup Cowkur

Reputation: 20563

You can use a simple RawQuery like this:

private SQLiteDatabase mDatabase;

Cursor c = mDatabase.rawQuery("select COLUMN_NAME from TABLE_NAME",null);

int count = c.getCount();

The Cursor.getCount() method returns the number of rows in the cursor, whch in this case would be the number of items you are looking for.

Upvotes: 1

Chintan Khetiya
Chintan Khetiya

Reputation: 16152

Try This

private static final String DB_TABLE_PLACES = "Places";
private SQLiteDatabase mDatabase;

private long fetchPlacesCount() {
    String sql = "SELECT COUNT(*) FROM " + DB_TABLE_PLACES;
    SQLiteStatement statement = mDatabase.compileStatement(sql);
    long count = statement.simpleQueryForLong();
    return count;
}

See More Here.

Upvotes: 11

Related Questions