sqlite Android Cursor Index out of Bound Exception

dphi5xsq  于 2023-05-18  发布在  SQLite
关注(0)|答案(3)|浏览(94)

这段代码有什么问题吗?2我想用条形码查询数据,结果显示光标索引越界异常。

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;
}
c6ubokkw

c6ubokkw1#

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;
}
9o685dep

9o685dep2#

moveToFirst()方法的文献:

**public abstract boolean moveToFirst()**将光标移动到第一行。如果游标为空,此方法将返回false。
返回移动是否成功。

所以你的moveToFirst调用失败了(因为cussor有0个元素),这就是崩溃的原因。
这样做:

if(c != null && c.moveToFirst()) {
    String id = c.getString(0);
    Log.v(id, id + "Id" );
    return id;
}
mrfwxfqh

mrfwxfqh3#

试试这个

String id;
if (c!= null && c.moveToNext){
   String id = c.getString(0);
   return id;   
 }

相关问题