OGeek|极客世界-中国程序员成长平台

标题: Android 光标索引超出范围异常 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-9 06:50
标题: Android 光标索引超出范围异常

这段代码有什么问题吗,我想使用条形码查询数据,它显示光标索引超出范围异常。

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



Best Answer-推荐答案


光标中没有结果。您应该检查 moveToFirst() 返回的内容(很可能是 false)。此外,您应该使用 moveToNext(),而不是 moveToFirst()。还要注意你没有检查 ss 参数。这可能导致 SQL 注入(inject)漏洞。你应该使用参数。另外我认为您可以在方法中使用单个返回。

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

关于Android 光标索引超出范围异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17633091/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://www.ogeek.cn/) Powered by Discuz! X3.4