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.

2
  • Why are you not using SQL to query data? Commented Feb 26, 2017 at 11:06
  • I'm also using a content providers to work better with data Commented Feb 26, 2017 at 11:16

1 Answer 1

2

In SQL, you can simply do:

select sum(col), avg(col) from table;
Sign up to request clarification or add additional context in comments.

3 Comments

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. - Take a look at this answer - stackoverflow.com/questions/20582320/…
Okay. Ahaha it works, I noticed that I didn't write everything correct. Thank you I will accept you answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.