Kenneth Kenneth - 6 months ago 166
Android Question

Sugar ORM SUM a column

Does anyone know if it is possible to sum a column using Sugar ORM? I've tried to find any documentation, and there is a raw query method, however, the raw query method does not have any returning values.

Example: "select sum(price) from atable"

Class.executeQuery() is void.

Sugar ORM does not seem very usable until this kind of features (along with JOIN etc) are present.


I finally do it with the following code:

long sumValue = -1L;
Database db = ((Application)SugarApp.getSugarContext()).obtainDatabase();
SQLiteDatabase sqLiteDatabase = db.getDB();
SQLiteStatement sqLiteStatement = sqLiteDatabase.compileStatement(
    "SELECT SUM(column_name) FROM table_name");
try {
    sumValue = sqLiteStatement.simpleQueryForLong();
} catch (Exception var16) {
} finally {

Also need to change the Application class to can access to the DataBase property because has protected access (don't forget to modify the manifest properly).

public class Application extends SugarApp {    
    public Database obtainDatabase(){
        return getDatabase();

Hope it helps.