-1

I am new here and want to ask regarding android studio using sqLite. I want to SUM all the data that store in a column and display it in textview. I am new in programming and I little bit confused bcs it keep not showing the total sum of the column of the table. here is the code that I build my self. thank you.

//HERE IS THE DB CREATION

public void createdb(){
    db1 = this.openOrCreateDatabase("dbshops",MODE_PRIVATE,null);
    String sqlcreate = "CREATE TABLE IF NOT EXISTS shops" +
            "(ITEMS VARCHAR NOT NULL,PRICE DOUBLE);";
    db1.execSQL(sqlcreate);
}

// HERE IS THE METHOD THAT I USED FOR SUM PRICE COLUMN:

public void calculatePrice(){
    results = (TextView)findViewById(R.id.resulttextView);
    try {
        String sqlcalculate = "SELECT SUM(PRICE) FROM shops";
        db1.execSQL(sqlcalculate);
        Cursor c = db1.rawQuery(sqlcalculate, null);
        if (c.moveToFirst()) {
            results.setText("TOTAL PRICE = " + c.getInt(c.getColumnIndex("price")));
            return;
        }
    }catch (Exception e){
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

1

You're confusing the terms row and column.

Try:

String sqlcalculate = "SELECT SUM(PRICE) AS PriceTotal FROM shops";

and then

results.setText("TOTAL PRICE = " + c.getInt(c.getColumnIndex("PriceTotal")));

By doing so, you are creating an "alias" (calculated) column named PriceTotal and then you are retrieving it.


By the way, remove this useless line

db1.execSQL(sqlcalculate);
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115