【问题标题】:ArrayIndexOutOfBoundException only when the array length is equal to one [closed]ArrayIndexOutOfBoundException 仅当数组长度等于一时[关闭]
【发布时间】:2013-01-13 10:52:34
【问题描述】:

我有一个收集 rawQuery 结果的数组。它工作得很好,但是当它只有一个结果时会抛出这个异常。

public String [][] getList() {
        SQLiteDatabase db = this.getWritableDatabase();
        String [][] data;
        Cursor c = db.rawQuery("SELECT nombre FROM productos GROUP BY " +
            "nombre ORDER BY nombre", null);
        if (c.moveToFirst()) {
            data = new String[c.getCount()][1];
            int i = 0; char last = 1;
            do {
                data[i][0]=c.getString(c.getColumnIndex("nombre"));
                if(data[i][0].charAt(0)!=last) {
                            char [] a = {data[i][0].charAt(0)};
                String b = new String(a); 
                            data[i][1]=b; 
                            last = a[0];} else {
                    data[i][1]=null;
                }
                i++;
            } while ( c.moveToNext());
            db.close();
            return data;
        }
        data=new String[1][1]; data[0][0]="-1";
        db.close();
        return data;
    } 

该方法向自定义列表适配器提供了构建带有分隔符的 listView 所需的信息(这就是我在第二列中使用字符的原因)。你能帮帮我吗?

【问题讨论】:

    标签: android arrays listview cursor adapter


    【解决方案1】:

    您正在将 data 初始化为数组 new String[c.getCount()][1]。这意味着最高有效的第二个下标是 0,而不是 1。你想要一个双元素数组:new String[c.getCount()][2]

    【讨论】:

    • 谢谢!但问题仍然存在。例如,当我有两个结果时,它工作得很好,只有当有一个结果时才会失败。
    • 我又试了一次,现在可以了!非常感谢!
    • @Buni - 也许您可以accept the answer 向其他人表明问题已解决。
    猜你喜欢
    • 1970-01-01
    • 2014-01-27
    • 2015-02-23
    • 1970-01-01
    • 2019-01-19
    • 2019-03-26
    • 1970-01-01
    • 2019-12-17
    • 2020-04-25
    相关资源
    最近更新 更多