错误:在从中访问数据之前,确保Cursor已正确初始化?

时间:2014-04-20 04:27:05

标签: java android sql sqlite

我将游标初始化如下:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...Code, code, code...

        c = db.query("US_States", null, null, null, null, null, null, null);


    }

游标本身在同一活动中的单独方法中使用:

public void GameStart()
    {
        int gameCount = 0;
        while(gameCount < 5)
        {
            cursorEntry = new Random().nextInt(c.getCount());
            c.moveToPosition(cursorEntry);
            cursorState = c.getString(1);
            cursorCapital = c.getString(2);
            displayText.setText(cursorState);

它给了我以下错误:

E/CursorWindow﹕ Failed to read row 20, column 2 from a CursorWindow which has 50 rows, 2 columns.

每次重新运行应用程序时,堆栈跟踪指向此行cursorCapital = c.getString(2);。它总是在那里出错。

数据库是这样的:

State|Capital
Alabama|Montgomery
Alaska|Juneau
Arizona|Phoenix
...The rest of the states

我在SO上阅读了几篇类似的帖子,但他们并没有让我知道出了什么问题。任何输入都表示赞赏。

1 个答案:

答案 0 :(得分:12)

游标的列索引从零开始,因此更改:

 cursorState = c.getString(1);
 cursorCapital = c.getString(2);

cursorState = c.getString(0);
cursorCapital = c.getString(1);