Search code examples
androidsqlitekotlinbooleanandroid-sqlite

Get Count of rows with value true from a database in android kotlin


I have a database, with names and true or false values. I have for example 10 rows and four of them have got the value "true".

name | value  
-------------  
1    | false  
2    | true  
3    | false  
4    | true  
5    | false  
6    | false  
7    | true  
8    | false  
9    | false  
10   | true

my try is:

val c = db!!.rawQuery("SELECT COUNT(*) FROM table GROUP BY value HAVING value = \"true\"", arrayOf())  
c.moveToNext()  
Log.e("OUTPUT", c.toString())

but the log I will get is:
E/OUTPUT: android.database.sqlite.SQLiteCursor@b0b20ea

So my question is, how to get the countnumber as a usable Integer value?


Solution

  • First correct your query like this:

    val c = db!!.rawQuery("SELECT COUNT(*) FROM table WHERE value = 'true'"
    

    because you don't want to group by value but count the rows of the tables that contain the value 'true'.
    I assume that the column value contains strings.
    If it contains booleans then the query should be:

    val c = db!!.rawQuery("SELECT COUNT(*) FROM table WHERE value"
    

    Then you can extract the value of the 1st and only column of the cursor by c.getInt(0):

    Log.e("OUTPUT", c.getInt(0).toString())