Antimony Antimony - 2 months ago 9
Android Question

SQLite: How to get average of long type values

I'm making an app that records the timestamp of touchscreen actions made my the user.

Then, after recording the readings in an SQLite table, I take the average of each column at the end. However, I'm getting an error:

E/AndroidRuntime(1344): java.lang.NumberFormatException: Invalid long: "1.40024e+08"


This happens when I try to take the average of each column, which I'm doing like so:

public long[] getAvg()
{
String selectQuery = "SELECT AVG(dwell_1), AVG(dwell_2), AVG(dwell_3), AVG(dwell_4), AVG(dwell_5), AVG(dwell_6), AVG(dwell_7), AVG(dwell_8), AVG(dwell_9), AVG(flight_12), AVG(flight_23), AVG(flight_34), AVG(flight_45), AVG(flight_56), AVG(flight_67), AVG(flight_78), AVG(flight_89) FROM " + TABLE;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

long[] row = new long[17];

if (cursor.moveToFirst()) {
for (int j=0; j<17; j++)
row[j] = Long.parseLong(cursor.getString(j));


}

return row;

}


It seems to be a function of the way the SQLite query displays the results. Is there any way I can circumvent/solve this? I require the precision by the way, so I can't use int or something else instead.

Oddly enough, when I run a query to just straight up display every record in the table, it works fine.

Any help will be greatly appreciated. Thanks in advance!

Answer

Try this :

 public long[] getAvg()
 {
      String selectQuery = "SELECT  AVG(dwell_1), AVG(dwell_2), AVG(dwell_3),  AVG(dwell_4), AVG(dwell_5), AVG(dwell_6), AVG(dwell_7), AVG(dwell_8), AVG(dwell_9), AVG(flight_12), AVG(flight_23), AVG(flight_34), AVG(flight_45), AVG(flight_56), AVG(flight_67), AVG(flight_78), AVG(flight_89) FROM " + TABLE;

      SQLiteDatabase db = this.getWritableDatabase();
      Cursor cursor = db.rawQuery(selectQuery, null);

      long[] row = new long[17];

      if (cursor.moveToFirst()) {
          for (int j=0; j<17; j++)
               row[j] =  cursor.getLong(j);
      }

      return row;
 }
Comments