【问题标题】:Receive an ArrayIndexOutOfBoundsException when trying to access String array尝试访问字符串数组时收到 ArrayIndexOutOfBoundsException
【发布时间】:2013-04-16 04:33:12
【问题描述】:

我有一个模型lineModel,我用它来为我的gridAdapter 填充一个数组items当我手动填充条目时,我的模型工作正常。例如:

lineModel[] items = {
                new lineModel(2, "B", "", "#52D017", 5, 10, 30),
                new lineModel(3, "C", "", "#000000", 4, 8, 30),
};

但是,当使用 SQLite 填充 items 时,我会收到 ArrayIndexOutOfBoundsException

具体来说:

04-15 15:50:21.322: E/AndroidRuntime(26804): java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
04-15 15:50:21.322: E/AndroidRuntime(26804):    at com.idealiner.metrosleepuniversal.model.GridModel.getLines(GridModel.java:68)

第 68 行 是当我调用 lineModel 并使用光标中的值填充它时。

        items[i] = new lineModel(i, c.getString(c_line), c.getString(c_name), c.getString(c_ccolor), 0, 0, 0); 

方法getLines() 应该返回对象数组,但我相信在while() 循环中的某个地方存在问题,很可能是在填充数组时。

任何帮助/建议/指导将不胜感激。

整个方法getLines如下:

public lineModel[] getLines() {

    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();


    String[] sqlSelect = {"*"}; 
    String sqlTables = "lines";

    qb.setTables(sqlTables);
    Cursor c = qb.query(db, sqlSelect, null, null,
            null, null, null);


    lineModel[] items = {};

    int i=0;

    int c_line      = c.getColumnIndex("line_id");
    int c_name      = c.getColumnIndex("line_name");
    int c_ccolor    = c.getColumnIndex("line_color");
    int c_tcolor    = c.getColumnIndex("text_color");


    c.moveToFirst();

    if (c != null) {
        while(c.moveToNext()) {
            items[i] = new lineModel(i, c.getString(c_line), c.getString(c_name), c.getString(c_ccolor), 0, 0, 0); 
            i++;
        }
        c.close();
    }

    return items;
}

【问题讨论】:

    标签: android android-arrayadapter android-sqlite android-cursor


    【解决方案1】:

    好吧,你正在创建一个长度为零的数组:

    lineModel[] items = {};
    

    所以当您尝试分配给它时没有items[i]

    如果您可以使用 c.getCount(),正如 Flavio Faria 建议的那样,请将初始长度设置为该值。否则,我建议您在进行过程中使用ArrayList.add() 项目。您可以使用.toArray() 获取结果数组

    事实上,您可能会考虑使用 ArrayList 并将其作为返回值传递,这通常是个好主意。

    另一种选择——取决于你如何使用这些线模型项目——是传递一个迭代器而不是一个数组(因为你所做的实际上是迭代到一个数组中。

    【讨论】:

    • 谢谢,我要试试这个。
    【解决方案2】:

    您不能将"*" 与列名一起使用。您必须要么只使用"*",要么必须声明数组中的每一列。所以,不要这样做:

    String[] sqlSelect = {"0 _id", "*"}; 
    

    改为添加它们中的每一个:

    String[] sqlSelect = { "line_id", "line_name", "line_color", "text_color"}; 
    

    或者:

    String[] sqlSelect = { "*" }; 
    

    您还必须删除 c.moveToFirst() 调用以避免跳过光标的第一行,因为 c.moveToNext() 已经为您完成了这项工作。

    您的数组还必须足够大以容纳所有项目:

    lineModel[] items = new lineModel[c.getCount()];
    

    除此之外,请记住 Java 中的类名以大写字母开头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      相关资源
      最近更新 更多