gpt4 book ai didi

java - 当 WHERE 子句中的列为空时,我的 SQLite 查询会导致cursorindexoutofbounds 异常。我该如何阻止这个?

转载 作者:行者123 更新时间:2023-12-01 23:54:07 26 4
gpt4 key购买 nike

仅当 COLUMN_NAME_DATE 列为空(该表中未添加任何条目)时,才会发生此错误。一旦我添加了一些条目,它就可以正常工作。我已经尝试了各种空检查,以及什么没有,但没有任何效果。错误确切:

android.database.CursorIndexOutOfBoundsException: Index -1 requested, 
with a size of 0

这是错误的代码:

    if (cursor1.moveToFirst() == false) {
Toast.makeText(this, "No categories found.", Toast.LENGTH_LONG).show();
}
else {

for (int i = cursor1.getCount() - 1; i >= 0; i--) {
catTotal = 0;
cursor1.moveToPosition(i);
curCat = cursor1.getString(cursor1.getColumnIndexOrThrow(
CategoriesDbContract.TblCategories.COLUMN_NAME_CATEGORY));

cursor2 = db.query(TransactionsDbContract.TblTransactions.TABLE_NAME,
null,
TransactionsDbContract.TblTransactions.COLUMN_NAME_DATE + ">" + dateSent,
null, null, null, null);

for (int j = cursor2.getCount() - 1; j >= 0; j--) {
cursor2.moveToPosition(j);
catTotal += cursor2.getDouble(cursor2.getColumnIndexOrThrow(
TransactionsDbContract.TblTransactions.COLUMN_NAME_AMOUNT));
}

percent = catTotal/overallTotal * 100;
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(1);
String percStr = df.format(percent);

category += cursor1.getString(cursor1.getColumnIndexOrThrow(
CategoriesDbContract.TblCategories.COLUMN_NAME_CATEGORY)) + "\n";

spent += percStr + "\n";
}

最佳答案

我猜你的错误在这里:

for (int j = cursor2.getCount() - 1; j >= 0; j--) {
cursor2.moveToPosition(j); // j might be -1

...因为如果你的陈述...

cursor2 = db.query(TransactionsDbContract.TblTransactions.TABLE_NAME, ...);

...不返回任何行,cursor2.getCount() 为零,因此 j-1 开头。

我建议您使用...

while (cursor1.moveToNext()) {
catTotal = 0;
curCat = cursor1.getString(cursor1.getColumnIndexOrThrow(
CategoriesDbContract.TblCategories.COLUMN_NAME_CATEGORY));
cursor2 = db.query(...);

while (cursor2.moveToNext()) {
catTotal += cursor2.getDouble(cursor2.getColumnIndexOrThrow(
TransactionsDbContract.TblTransactions.COLUMN_NAME_AMOUNT));
}
}

...因为这样您就不需要 for 循环。

希望这有帮助......干杯!

关于java - 当 WHERE 子句中的列为空时,我的 SQLite 查询会导致cursorindexoutofbounds 异常。我该如何阻止这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15866719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com