androiddatabasedbflow

calculate SUM for single column with DbFlow


I'm using latest version of DBFLOW library and i'm trying to calculate sum single column as countOfNewPosts

this is my table:

public class CafeWebNewPostInformation extends BaseModel {
    @PrimaryKey
    @Column
    public int id;

    @Column
    public int cafeWebServerId;

    @Column
    public int countOfNewPosts;

    @Column
    @ForeignKey(tableClass = AlachiqCafeWebs.class,
            references = @ForeignKeyReference(columnName = "parentId", foreignKeyColumnName = "id"))
    private int parentId;

    @Column
    public int lastSavedId;

    @Column
    public int lastRequestedId;

    @Column
    public int lastRetrievedId;
}

and this is my code to get that from this table:

CafeWebNewPostInformation countOfNewPost =
        SQLite.select(
                Method.sum(CafeWebNewPostInformation_Table.countOfNewPosts).as("count")
        )
                .from(CafeWebNewPostInformation.class).querySingle();

i dont get any error and this is result of that:

ScreenShot:

enter image description here

what happen and where is count on this result?


Solution

  • problem solved

    think about it. you are calling

    SELECT SUM(`countOfNewPosts`) as 'count' FROM `CafeWebNewPostInformation`
    

    Meaning the results you get back only contain a single row of count from that query. You wont get any error since we don't implement strict column matching on a Cursor. You need to define a @QueryModel QueryModels that has a single field called count:

    @QueryModel // (add database reference)
    public class CountOfPost {
    
      @Column
      public int count;
    }
    

    then

    CountOfPost count = SQLite.select(
      Method.sum(CafeWebNewPostInformation_Table.countOfNewPosts).as("count"))
      .from(CafeWebNewPostInformation.class)
      .queryCustomSingle(CountOfPost.class);  
    

    or you can instead of calling querySingle() call count().

    reference