Android Cursor Index out of Bound Exception

允我心安 提交于 2019-11-30 18:45:29

问题


is there any thing wrong with this code, i want to query for data by using barcode and it show me that Cursor Index out of Bound exception .

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

回答1:


No results in the Cursor. You should check what moveToFirst() is returning (most likely false). Also you should use moveToNext(), not moveToFirst(). Also watch out that you're not checking ss parameter. This could lead to SQL injection vulnerabilities. You should be using parameters. Also I think you can use a single return in your method.

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:


The literature of moveToFirst() method:

public abstract boolean moveToFirst () Move the cursor to the first row. This method will return false if the cursor is empty.

Returns whether the move succeeded.

So your moveToFirst call is failing(because cusrsor has 0 elements) and that is the reason for crash.

Do this:

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



回答3:


try this

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


来源:https://stackoverflow.com/questions/17633091/android-cursor-index-out-of-bound-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!