Bringing a sum in Sqlite Android

Asked

Viewed 1,048 times

1

I have a problem in the development of an App, following, I have a list that all the data of donations in the bank, and in this Activity I created a Textview to receive the total value of those donations, however, I have some problems: 1° the value field in the database saved in TEXT Exp: 'R$ 120,00', 'R$ 325,65' and so I add with substr; 2° when I try to bring the result of that sum actually in the app comes out all the text of the query, I tried several ways and this is the current situation of my code:

    public String RetornarTotal(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor stmt = db.rawQuery("SELECT SUM(SUBSTR(VALOR,3,20)) FROM " + TABLE_NAME, null);

    String total = stmt.getColumnName(0).toString();
    //String total = stmt.execute();
    return total;
}

This method is called in the oncrete of Activity and is in the class Sqlhelper, I want to return only the value of that sum, could help me ?

2 answers

0

Use the method getColumnIndex to redeem the first value of your query. See below how it should be done:

Cursor stmt = db.rawQuery("SELECT SUM(SUBSTR(VALOR,3,20)) FROM " + TABLE_NAME, null); 

if (stmt.getCount() > 0) { 
    stmt.moveToFirst(); 
    do { 
           total = stmt.getString( stmt.getColumnIndex(0));
     } while (stmt.moveToNext()); 
         stmt.close(); 
     }
}
  • This do-while is unnecessary, including if, since this query will always return a single record, even if the database is empty (in this case it will result in sum equal to zero).

0

Just fix that line:

String total = stmt.getColumnName(0).toString();

For:

String total = stmt.getString(0);
stmt.close();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.