【问题标题】:Sqlite : ArrayIndexOutOfBoundsException when try to fetch array from databaseSqlite:尝试从数据库中获取数组时出现 ArrayIndexOutOfBoundsException
【发布时间】:2020-09-01 08:06:51
【问题描述】:

我在 sqlite 中创建了一个表,这里给我 java.lang.ArrayIndexOutOfBoundsException 是返回数组值时的代码。

    Cursor res = database.rawQuery("select "+QsDatabaseHelper.getItemName()+" from " + QsDatabaseHelper.getItemTableName(), null);
    String[] array = new String[res.getCount()];
    int i = 0;
    while(res.moveToNext()){
        String itemName = res.getString(res.getColumnIndex( QsDatabaseHelper.getItemName()));
        array[i] = itemName;
        Log.d("VALUE ",itemName+"name"); //There i geting all values
        i++;
    }
    return array[i]; //error showing this line

在我的片段中,我调用此函数来获取字符串 [] 中的项目名称

           String[] ItemNameArray = new String[list_counts];
                    for (int i = 0; i < list_counts; i++) {
                        ItemNameArray[i] = listcatDb.itemname();
                    }

【问题讨论】:

    标签: android arrays database sqlite cursor


    【解决方案1】:

    你只是返回数组。因为 i 值在 while 循环内增加。所以只需返回数组然后在主线程中使用数组值,或者如果你想返回字符串使用 i-1;

    return array; 
    

    【讨论】:

    • 谢谢,我没有注意到这个错误,更新代码后我得到了正确的响应
    【解决方案2】:

    当索引为负数或大于或等于数组大小时,将引发异常ArrayIndexOutOfBounds。 在while循环中,'i'的值超过了数组的大小.. 所以应该是这样的

    return array[i-1];
    

    而不是,

    return array[i];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-27
      • 2012-06-06
      • 2012-11-28
      • 1970-01-01
      • 2013-04-17
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多