我有这个方法:
public String givenCheckmark(String name, String date)
{
SQLiteDatabase db = Cache.openDatabase();
Cursor cursor = db.rawQuery("select value from checkmarks where timestamp ='"+date+"' and habit ='"+name+"'", null);
String habitValue = "";
cursor.moveToFirst();
if (!(cursor == null)) {
habitValue = Integer.toString(cursor.getInt(0));
}
cursor.close();
return habitValue;
}
由于某种原因,如果我删除了
habitValue = Integer.toString(cursor.getInt(0));
应用程序不会崩溃。所以问题一定出在cursor.getInt(0)上。该查询仅返回一行。我猜光标不在第一行,但是......为什么??
最佳答案
最可能的原因是索引“0”处的项目不是整数。另一个原因是游标本身可能为空。最后,您可能必须检查是否确实返回了值。
要解决第一部分,您需要使用 Cursor#getColumnIndex()
来获取您尝试检索的列的索引。因此,如果它是您想要的“id”,那么您会这样做:
int id = curve.getInt(cursor.getColumnIndex("id"));
要解决第二部分,您需要确保返回结果。为此,您只需检查 Cursor#getCount()
。所以:
boolean isEmpty =cursor.getCount() == 0;
或者,如果光标为空,则 Cursor#moveToFirst()
的返回值实际上会返回 false
,这意味着您可以使用如下方式检索值:
if (cursor != null && cursor.moveToFirst()) {
// The cursor is not null and contains elements. Continue retrieving values.
}
对于第三部分,您可以使用 Cursor#isNull() 来检查给定索引处是否有值。所以像这样:
boolean doesNotHaveValue = cursor.isNull(cursor.getColumnIndex("id"));
我在这里看到的其他问题是,您在将光标移动到第一个索引后检查光标是否为空,这意味着您将得到一个 NullPointerException
,无论光标是否为空。无论游标是否为空,您都会关闭游标。
关于java - 应用程序因cursor.getInt()而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309325/