0

I tried this to get the count of rows. But the program is hanging.

private int countbaglist()
{
    int count = 0;
    SQLiteDatabase db = datasource.getWritableDatabase();
    Cursor cursor = db.rawQuery(
        "select count(*) from shoplist where itemname=?",
        new String[] { String.valueOf("itemname") });

    while(cursor.moveToFirst())
    {
        count = cursor.getCount();
    }
    return count;
}
Graham Borland
  • 60,055
  • 21
  • 138
  • 179
SIDDHI
  • 129
  • 3
  • 11

2 Answers2

2

try this link for your answer

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

remove the while condition in your code below:

  while(cursor.moveToFirst()){
    count = cursor.getCount();
  }

replace below code:

count = cursor.getInt(0)
Community
  • 1
  • 1
Dinesh
  • 6,500
  • 10
  • 42
  • 77
2

It's hanging because your while loop never exits. Replace the while with a one-time if check instead. Also, note that you need to read the integer value returned from the COUNT query, rather than the cursor's row count which will always be 1.

if (cursor.moveToFirst())
    count = cursor.getInt(0);
Graham Borland
  • 60,055
  • 21
  • 138
  • 179
  • Downvoter, explain yourself. My answer is the only correct one so far. – Graham Borland Apr 27 '12 at 09:53
  • cursor.getInt(0); it's return no of row in a table? or cursor.getCount(); it's return no of row in a table? explain how it works..! – Dinesh Apr 27 '12 at 09:56
  • `cursor.getInt(0)` returns the integer result of the query, `COUNT(*)`, which is the number of items in the table. `cursor.getCount()` returns the number of rows **returned by the query**, which is totally different. – Graham Borland Apr 27 '12 at 09:57
  • @imrankhan because it was wrong, until I pointed out your mistake and then you fixed it. – Graham Borland Apr 27 '12 at 09:59