You should always moveToFirst()
the cursor before accessing its content.
By doing so, there wouldn't be any problems even if the cursor returned 0 row.
Question
I want to get the average value of a selection of a column. I'm trying to use SQL's AVG(X) function, but am not sure how. Here's what I've tried, but I get a CursorIndexOutOfBoundsException when calling c.getDouble(0)
. How should I do this?
String q = "SELECT AVG(" + KEY_PERCENT_GRADE + ") FROM " + TABLE_GRADES
+ " WHERE " + KEY_CATEGORY_ID
+ " = '" + catId +"'"; //catId is an int
Cursor c = db.rawQuery(q,null);
double d = c.getDouble(0);
Solution
You should always moveToFirst()
the cursor before accessing its content.
By doing so, there wouldn't be any problems even if the cursor returned 0 row.