我遇到了另一个奇怪的问题,我只是不明白。
我正在使用 max 将双打保存到我的数据库中。小数点后3位。双打已正确存储在数据库中,但是当我尝试获取数据并添加/乘以存储的双打时,我遇到了一个奇怪的问题
如果我存储的数据只有小数点后一位,一切正常,我得到正确的结果。但是,如果我在小数点后添加 2 位或更多位,我的整个计算将不起作用。我的 TextViews 没有结果。
我试图了解几个小时以来发生的事情,但我只是不明白为什么会发生这种情况。
这是代码:
我的 MainActivity,TextViews 获取文本的地方:
public void calc() {
// Get text for the statistics
amount_widget.setText(db.getSearchResult("amount", 0));
lpayment_widget.setText(db.getSearchResult("price", 0));
tpayment_widget.setText(db.getSearchResult("total_price", 1));
mileage_widget.setText(db.getSearchResult("mileage", 2));
trefueled_widget.setText(db.getSearchResult("amount", 1));
// Calculate text for the consumption
double consumption = (Double.parseDouble(db
.getSearchResult("amount", 1)) / Double.parseDouble(db
.getSearchResult("mileage", 2))) * 100;
consumption = Math.round(consumption * 100) / 100.0;
consumption_widget.setText(consumption + "L /100km");
}
正在获取和计算代码的我的数据库活动:
public String getSearchResult(String sql, int cmd) {
if (cmd == 0) {
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
String tmp = cursor.moveToFirst() ? cursor.getString(0) : "0";
cursor.close();
return tmp;
} else if (cmd == 1) {
double sum = 0;
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME;
String idQuery = "SELECT _id FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
Cursor id = db.rawQuery(idQuery, null);
// berechnung
cursor.moveToFirst();
id.moveToFirst();
int maxId = Integer.parseInt(id.getString(0));
for (int i = 0; i < maxId; i++) {
double tmp = Integer.parseInt(cursor.getString(0));
sum = sum + tmp;
cursor.moveToNext();
}
cursor.close();
id.close();
return String.valueOf(sum);
} else if (cmd == 2 && sql == "mileage") {
double sum = 0;
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME;
String idQuery = "SELECT _id FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
Cursor id = db.rawQuery(idQuery, null);
// berechnung
cursor.moveToFirst();
id.moveToFirst();
int maxId = Integer.parseInt(id.getString(0));
if (maxId > 1) {
int array[] = new int[maxId];
// Array füllen
for (int i = 0; i < maxId; i++) {
array[i] = Integer.parseInt(cursor.getString(0));
// sum = sum + tmp;
cursor.moveToNext();
}
for (int k = 1; k < maxId; k++) {
double tmp;
tmp = array[k] - array[k - 1];
sum = sum + tmp;
}
cursor.close();
id.close();
return String.valueOf(sum);
} else {
return "--";
}
}
return "Wrong CMD";
}