I am trying to get the total count of rows from Sqlite DB. Following is the code snippet of what I am trying 开发者_如何学Pythonto do.
I dont know what I am doing wrong here ?
public static int getTotalCount(Context _context)
{
Cursor c = null;
try
{
c = getInstance(_context).db.rawQuery("SELECT COUNT(word) FROM "
+ WORD_TABLE, null);
return c.getInt(c.getColumnIndex(WORD_COL));
} catch (Exception e)
{
Log.e("getTotalCount", e.toString());
}
return 0;
Exception message : 05-08 05:21:19.934: ERROR/getTotalCount(440): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
Try c.getInt(0);
or
c = getInstance(_context).db.rawQuery("SELECT COUNT(word) as WORD_COL FROM "
+ WORD_TABLE, null);
also put a c.moveToFirst();
right after the rawQuery line for good measure.
Assuming WORD_COL
is word
? You have not requested a column named word
. You have a column COUNT(word)
, which is a completely different matter; thus when you try to fetch data for word
, getColumnIndex
fails to find it, giving you a nonsense index of -1
, which then causes the getInt
to fail since nobody counts from -1
up. :)
You can rename the column to something nicer, too: SELECT COUNT(word) AS word_count FROM...
, then request that name. Another option is, you know this query returns only one column, there is no need to name it; just use its index directly.
After the rawQuery
, try
c.moveToFirst();
return c.GetInt(0);
try out this:
Cursor c = _sqlDatabase.rawQuery("Select * from table", null);
System.out.println("Count:"+c.getCount());
regards, Nital Shah
You may have this CursorIndexOutOfBoundsException
because the cursor doesnt point to the first result.
Try this:
try
{
c = getInstance(_context).db.rawQuery("SELECT COUNT(word) FROM "
+ WORD_TABLE, null);
c.moveToFirst();
return c.getInt(c.getColumnIndex(WORD_COL));
} catch (Exception e)
精彩评论