mercredi 31 décembre 2014

How To Use SQLite COUNT in Android to return number of rows


Vote count:

0




I want to write a query that add up all the rows that have the string value of "left" in column named DIRECTION. Next I want to return this sum.


In my code snip-it below assume data and data base are established.


Here is the prototype:



public int getSumLeft() {
String selectQuery = "SELECT COUNT( "+TableData.TableInfo.DIRECTION+" ) WHERE "+TableData.TableInfo.DIRECTION+" = left";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
int sum = cursor.getInt(0);
cursor.close();
return sum;
}


I've tried several queries and this one seems to be the closes to what I need. I think the problem is with statement 'int sum = cursor.getInt(0);'


I think the zero parameter is overriding the results. When I remove the zero the code breaks. getInt is an SQLite function that is used to access data in the database. I did not create that function. But I must use it or and another function like it.


Also, do I need to put a while loop around the query to move the cursor for a COUNT query? Doesn't the Database count for you, therefor no need for iteration?


Is there another way of counting the rows where the string value is 'left' and the sum can be returned?


Full code here:


Database: http://ift.tt/1xABS7u


Implementation (see the button in onCreate function ): http://ift.tt/1rBHtuT


Thanks for looking into this.



asked 44 secs ago

Leoa

428






How To Use SQLite COUNT in Android to return number of rows

Aucun commentaire:

Enregistrer un commentaire