1

Goodmorning everyone!

I am trying to get sum and average from a column of a sqlite database in android. Searching I found so many ways, I tried them unsuccessfully.

To get the number of values in a column I've used:

cursor.getCount() // with the cursor in the right column

And it works. My problem is how to get the sum. This is the method I "built":

public void setValues()
{
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    String[] projection = {
            _ID,
            DiabeticContract.DiabeticEntry.COLUMN_GLYCAEMIA_VALUES,
    };


    Cursor curs = db.query(
            DiabeticContract.DiabeticEntry.TABLE_NAME,   
            projection,            
            null,                  
            null,                  
            null,              
            null,                  
            null );                  

    curs.moveToLast();

    double lastGlycValue = curs.getDouble( curs.getColumnIndex("Glycaemia") );
    double percent = (lastGlycValue + 46.7) / 28.7;
    double mmol = ((percent  - 2.15) * 10.929);

    LastGlyc.setText(String.format("%.2f" ,lastGlycValue));
    Percent.setText(String.format("%.2f" ,percent));
    mMol.setText(String.format("%.2f" ,mmol));
}

It's without cursor.getCount() to make it more clear.

Thank you for your help.

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
Mark.
  • 49
  • 1
  • 12

1 Answers1

2

In SQL, you can simply do:

select sum(col), avg(col) from table;
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
  • Yes I know, i tried it in terminal and it works. But i can't from "android". Or if i can, i don't know how – Mark. Feb 26 '17 at 11:15
  • @Mark. - Take a look at this answer - http://stackoverflow.com/questions/20582320/android-get-sum-of-database-column – Gurwinder Singh Feb 26 '17 at 11:17
  • Okay. Ahaha it works, I noticed that I didn't write everything correct. Thank you I will accept you answer. – Mark. Feb 26 '17 at 11:30