当前位置: 首页 > 知识库问答 >
问题:

请求的CursorIndexOutOfBounds异常索引0,大小为0

双志强
2023-03-14

我正在尝试从数据库的某一行获取文本。为此,我做了这个函数

public String getTranslation(long rowId) throws SQLException {    
    String str = null;
    Cursor mCursor = db.query(
        true, TABLE_LANGUAGE_FR, new String[] {
            KEY_ID_INTERFACE_TEXT, KEY_ITEM_NAME,KEY_FORM_LABEL_ID, KEY_FORM_RANK
        }, 
        KEY_FORM_LABEL_ID + "=" + rowId, null, null, null, null, null
    );

    if (mCursor != null) {
        mCursor.moveToFirst();
        str = mCursor.getString(mCursor.getColumnIndex(KEY_ITEM_NAME));
    }
    return str;
}

我这样称呼它:

db = new DbAdapter(this);
db.createDatabase(); 
db.openDataBase();
String str = db.getTranslation(1706);

我的桌子看起来像这样:

我得到这个错误:

09:32:08.965    307 com.Orange  ERROR   AndroidRuntime  Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
09:32:08.965    307 com.Orange  ERROR   AndroidRuntime      at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
09:32:08.965    307 com.Orange  ERROR   AndroidRuntime      at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
09:32:08.965    307 com.Orange  ERROR   AndroidRuntime      at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
09:32:08.965    307 com.Orange  ERROR   AndroidRuntime      at com.Orange.Database.DbAdapter.getTranslation(DbAdapter.java:141)
09:32:08.965    307 com.Orange  ERROR   AndroidRuntime      at com.Orange.Authentication.onCreate(Authentication.java:32)

为什么我会犯这个错误?我做错了什么?

提前感谢。

共有3个答案

谢旻
2023-03-14

试着改变这条线

Cursor mCursor = db.query(true, TABLE_LANGUAGE_FR, new String[] {
           KEY_ID_INTERFACE_TEXT, KEY_ITEM_NAME,KEY_FORM_LABEL_ID, KEY_FORM_RANK}, 
                   KEY_FORM_LABEL_ID + "=" + rowId, null, null, null,
           null, null);

Cursor mCursor = db.query(TABLE_LANGUAGE_FR, new String[] {
           KEY_ID_INTERFACE_TEXT, KEY_ITEM_NAME,KEY_FORM_LABEL_ID, KEY_FORM_RANK}, 
                   KEY_FORM_LABEL_ID + "=" + rowId, null, null, null,
           null);

并将其添加到if条件中

 return str;
终翰学
2023-03-14

尝试使用

while(cursor.moveToNext())
{
   if(cursor.isFirst())
   {
      //Your code goes here in your case
      return mCursor.getString(mCursor.getColumnIndex(KEY_ITEM_NAME));
   }
}
finaly
{
 if(mCursor!= null)
 {
   mCursor.close();
 }
}
姬墨竹
2023-03-14

看起来你有一个emtpy光标。请尝试检查,而不是检查它是否为空

if(mCursor.getCount() > 0)
{
  //do stuff
}

尝试删除where条件,以确保在运行select语句时实际获取数据。如果仍然没有任何结果,则可能是表名输入错误,或者无法连接/创建数据库/表。

Cursor mCursor = db.query("sys_interface_text", new String[] {
       "id_interface_text", "item_name","form_label_id", "form_rank"}, 
               "form_label_id = 1706", null, null, null,
       null);
 类似资料: