得到" CursorIndexOutOfBoundsException"

时间:2013-12-31 13:54:07

标签: java android sqlite

我正在尝试检索sqlite数据库的数据。并将其放在一个字符串上以进一步显示它但我收到此错误,请帮助我解决错误!

这里是显示错误的logcat数据

    12-31 13:18:55.141: E/1.6(3833): 2222
12-31 13:18:55.191: E/1.2.2(3833): android.database.CursorIndexOutOfBoundsException: Index 9 requested, with a size of 9
12-31 13:18:55.191: E/1.7(3833): 2222

这是显示错误的代码片段。

public String getdata() {
        // TODO Auto-generated method stub
        Log.e("1.1", "2222");
        String[] column = new String[]{KEY_ROWID, KEY_NAME, KEY_HOTNESS };
        Log.e("1.2", "2222");
        Cursor c = ourDatabase.query(DATABASE_TABLE, column, null, null, null, null, null);
        Log.e("1.3", "2222");
        String result = "";
        Log.e("1.4", "2222");

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iHotness = c.getColumnIndex(KEY_HOTNESS);
    Log.e("1.5", "2222");

    try{
        for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext());
        {
            Log.e("1.6", "2222");

            result = result + c.getString(0) + " " + c.getString(1) + " " + c.getString(2) + "\n";
        }
    }catch(Exception e)
    {

        Log.e("1.2.2", e.toString());
    }

    Log.e("1.7", "2222");
    return result;
}

注意:将以下代码放入try catch后,它将转移到下一个活动但未显示任何结果数据

        for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext());
        {
            Log.e("1.6", "2222");

            result = result + c.getString(0) + " " + c.getString(1) + " " + c.getString(2) + "\n";
        }

下一个活动代码:

TextView tv = (TextView) findViewById(R.id.textView3);

    Log.e("1", "111111");
    HotOrNot info = new HotOrNot(this);
    Log.e("2", "111111");
    info.open();
    Log.e("3", "111111");
    String data = info.getdata();
    Log.e("4", "111111");
    info.close();
    Log.e("5", "111111");
    tv.setText(data);

    Log.e("6", "111111");
}

}

1 个答案:

答案 0 :(得分:1)

你的分号太多了:

for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()); // look here :(

...所以你的for循环运行到光标的末尾。之后你试图从光标中获取一些数据,但是失败了,因为你已经在最后一个条目之后了。

只需使用这个:

while(c != null && c.moveToNext())
{
    Log.e("1.6", "2222");

    result = result + c.getString(0) + " " 
                    + c.getString(1) + " " 
                    + c.getString(2) + "\n";
}

您最有可能跳过c != null