dimanche 22 mars 2015

Saving SQLite list as an array: Not Working

I have an SQLite Database, and within it, one of the columns stores Strings which include numbers. I am trying to retrieve the numbers, store them as doubles in an array, and then take the mean of the array. However, it's not working. The App crashes every time I get to that part. I know the problem has to be somewhere within the array because I am able to list the SQLite Database as a string.



public int getDataCount() {
String countQuery = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}


public double databaseAverage(){
String dbString = "";
int dbInt = 0;
double dbDouble = 0;

SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";

Cursor c = db.rawQuery(query, null);
c.moveToFirst();

int rowCount = getDataCount();

Double[] array = new Double[rowCount];
int i = 0;

while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("productname")) != null) {
dbString += c.getString(c.getColumnIndex("productname"));

dbInt = Integer.parseInt(dbString.replaceAll("[\\D]",""));


dbDouble = (double) dbInt;


array[i] = dbDouble;
i++;

}
c.moveToNext();
}
db.close();


double sum = 0;

for(int v=0; v < array.length ; v++) {
sum = sum + array[i];
}

double average = sum / array.length;

return average;

}

Aucun commentaire:

Enregistrer un commentaire