Search code examples
javaandroidsqliteandroid-sqlite

getting output of a query in sqlite - android


you get data out of the columns using pre-provided methods such as getInt(...), getString(...), but how do you get data out of something like a SELECT statement, in sqlite the statement I'd like to do something like:

SELECT COUNT(COLUMN_NAME) FROM TABLE_NAME

how would you execute this query and then get the result to an int variable?


Solution

  • You do it the same way:

    String sql = "SELECT COUNT(COLUMN_NAME) FROM TABLE_NAME";
    

    So if you create a Cursor object with rawQuery():

    Cursor c = db.rawQuery(sql, null);
    

    this Cursor contains only 1 column and you can get its value with:

    if (c.moveToFirst()) result = c.getInt(0);
    

    where result is a predefined int variable.
    But it's a good practice to alias the returned column, like:

    String sql = "SELECT COUNT(COLUMN_NAME) AS counter FROM TABLE_NAME";
    

    so you can get it by its name:

    if (c.moveToFirst()) result = c.getInt(c.getColumnIndex("counter"));