这段代码有什么问题吗?我想使用条形码查询数据,它显示了光标索引越界异常。
public String getIdByBarcode(String ss) throws SQLException{
String[] column = new String[]{Pro_ID,Pro_Barcode, Pro_Name,Pro_NameKhmer, Pro_Quantity, Pro_Price, Pro_Description, Pro_Date};
Cursor c = ourDatabase.query(TABLE_NAME, column, Pro_Barcode + "= '" + ss + "' " , null, null, null, null);
if(c != null){
c.moveToFirst();
String id = c.getString(0);
Log.v(id, id + "Id" );
return id;
}
return null;
}发布于 2013-07-14 02:41:43
Cursor中没有结果。您应该检查moveToFirst()返回的内容(最有可能是false)。此外,您应该使用moveToNext(),而不是moveToFirst()。还要注意,您没有检查ss参数。这可能导致SQL注入漏洞。您应该使用参数。另外,我认为你可以在你的方法中使用一个返回。
public String getIdByBarcode(String ss) throws SQLException {
String[] column = new String[]{Pro_ID,Pro_Barcode, Pro_Name,Pro_NameKhmer, Pro_Quantity, Pro_Price, Pro_Description, Pro_Date};
final String args = new String[1];
args[0] = ss;
Cursor c = ourDatabase.query(TABLE_NAME, column, Pro_Barcode + " = ?" , args, null, null, null);
String ret = null;
if(c.moveToNext()) {
ret = c.getString(0);
}
return ret;
}发布于 2013-07-14 02:44:38
有关moveToFirst()方法的文献:
公共抽象布尔moveToFirst ()将光标移动到第一行。如果光标为空,此方法将返回false。
如果移动成功,将返回。
所以你的moveToFirst调用失败了(因为cusrsor有0个元素),这就是崩溃的原因。
执行以下操作:
if(c != null && c.moveToFirst()) {
String id = c.getString(0);
Log.v(id, id + "Id" );
return id;
}发布于 2013-07-14 02:41:30
尝尝这个
String id;
if (c!= null && c.moveToNext){
String id = c.getString(0);
return id;
}https://stackoverflow.com/questions/17633091
复制相似问题