jersam515
jersam515

Reputation: 657

How does one get the number of rows in an SQL database?(Android SDK)

I looked for this on SO and saw this(and others like it): sql direct way to get number of rows in table, however, Select is shown as a token as is count. I tried to use mDb.execSQL() but that only returns void. Any help on how to do this would be appreciated. The code is:
public int getRowNumber(){ return mDb.execSQL("SELECT COUNT(*) FROM notes");} I get an error that says "cannot return void result".

Upvotes: 1

Views: 570

Answers (2)

Pedantic
Pedantic

Reputation: 5022

The error you're getting means your method can't return void. execSQL itself returns a void, and you're returning that same void from your own method which is declared to return an int:

mDB.execSQL(...); // returns void
return mDB.execSQL(...); // re-returns void

public int foo() {
    return void; // error!
}

d.android.com link for reference.


I know you already accepted, but here's a quick & dirty test method that does what you sort of need to do:

    public int testCount() {
     Cursor c = m_db.rawQuery("select count(*) from mytable", null);
     int tst = 0;
     if (c.moveToNext()) {
         tst = c.getInt(c.getColumnIndex("count(*)"));
     }
     c.close();
     return tst;
  }

Upvotes: 2

kosa
kosa

Reputation: 66637

mDB.execSQL(...); returns void and your select query return counts that is why you are getting error. Instead you may use query (or) rawQuery like mDb.rawQuery("SELECT COUNT(*) AS cnt FROM notes",null); which returns Cursor, from Cursor get the 'cnt'.

Upvotes: 1

Related Questions