【问题标题】:Android Cursor Index out of Bound ExceptionAndroid 游标索引越界异常
【发布时间】:2013-07-13 18:35:19
【问题描述】:

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

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

【问题讨论】:

    标签: android sqlite cursor


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      moveToFirst()方法的文献:

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

      返回移动是否成功。

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

      这样做:

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

      【讨论】:

        【解决方案3】:

        试试这个

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

        【讨论】:

        • 在这里使用一段时间是没有意义的。 id 将始终获取最后一个元素。更不用说 id 无法从循环外部访问...
        猜你喜欢
        • 1970-01-01
        • 2019-03-08
        • 1970-01-01
        • 2017-09-08
        • 2011-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多