Ahmad Meer
Ahmad Meer

Reputation: 89

Sum of SQLite Table android

Im not seeing where I went wrong. I have a table where I want to check how many rows are stored if its more than seven then I will subtract the count - 7 and position the courser there to bring me the sum of the last seven But so far its returning CursorIndexOutOfBoundsException here is the code:

public Helper GetWeaklySum() {
SQLiteDatabase db = this.getReadableDatabase ();
Helper helper = new Helper ();
Cursor cursor = db.rawQuery ("SELECT SUM(Percent) FROM " + TABLE_PROGGRES, null);
Cursor counter = db.rawQuery ("SELECT * FROM " + TABLE_PROGGRES, null);


cursor.moveToFirst ();
counter.moveToFirst ();

if(cursor != null && !cursor.isAfterLast ()) {
    if(counter.getCount () < 7 && !cursor.isAfterLast ()){
        Helper.Sum_Weakley = cursor.getInt (0);
        cursor.moveToNext ();
    }else if(counter.getCount () >= 7 && !cursor.isAfterLast ()){
        for (int i = counter.getCount () - 7 ; i < counter.getCount(); i++) {
            cursor.moveToPosition(i);
            Helper.Sum_Weakley = cursor.getInt (0);
            cursor.moveToNext ();
        }
    }
    cursor.close ();
    }else if (cursor == null){
        return null;
    }
return Helper;
}

Upvotes: 1

Views: 81

Answers (1)

Kapil G
Kapil G

Reputation: 4141

Your cursor query which gives you sum

Cursor cursor = db.rawQuery ("SELECT SUM(Percent) FROM " + TABLE_PROGGRES, null);

will only return 1 row which will be sum of percent for all rows in the table. so cursor.moveToPosition will always give indexOutofBounds for greater than 1.

Cursor cursor = db.rawQuery ("SELECT SUM(Percent) FROM " + TABLE_PROGGRES, null);
Cursor counter = db.rawQuery ("SELECT Percent FROM " + TABLE_PROGGRES, null);


cursor.moveToFirst ();
counter.moveToFirst ();

if(cursor != null && !cursor.isAfterLast ()) {
    if(counter.getCount () < 7 && !cursor.isAfterLast ()){
        Helper.Sum_Weakley = cursor.getInt (0);
        cursor.moveToNext ();
    }else if(counter.getCount () >= 7 && !cursor.isAfterLast ()){
        int lastSevValue=counter.getCount() -7;
        Helper.Sum_Weakley=0;
       for(int i=lastSevValue;i<counter.getCount();i++){
            counter.moveToPosition(i);
            Helper.Sum_Weakley = Helper.Sum_Weakley+counter.getInt(0);
       }
    }
    cursor.close ();
    }else if (cursor == null){
        return null;
    }
return Helper;
}

You can also do it in 1 single query rather than 2 by using the below query. Try if you want-

SELECT SUM(Percent) FROM TABLE_PROGGRES LIMIT 7 OFFSET (SELECT COUNT(*) FROM TABLE_PROGGRES)-7;

Upvotes: 1

Related Questions