Java 错误:在访问 Cursor 中的数据之前,请确保它已正确初始化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23178441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: Make sure the Cursor is initialized correctly before accessing data from it?
提问by user3081519
I have cursor initialized as follows:
我的游标初始化如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...Code, code, code...
c = db.query("US_States", null, null, null, null, null, null, null);
}
The cursor itself is used in a separate method within the same activity:
游标本身在同一活动中的单独方法中使用:
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);
It gives me the following error:
它给了我以下错误:
E/CursorWindow﹕ Failed to read row 20, column 2 from a CursorWindow which has 50 rows, 2 columns.
With a stack trace pointing at this line cursorCapital = c.getString(2);
every time I rerun the application. It always gives an error there.
cursorCapital = c.getString(2);
每次我重新运行应用程序时,堆栈跟踪都指向这一行。它总是在那里出错。
The database something like this:
数据库是这样的:
State|Capital
Alabama|Montgomery
Alaska|Juneau
Arizona|Phoenix
...The rest of the states
I read a couple of similar posts on SO, but they didn't give me an idea of what is going wrong. Any input is appreciated.
我在 SO 上阅读了一些类似的帖子,但他们并没有让我知道出了什么问题。任何输入表示赞赏。
采纳答案by Shayan Pourvatan
The column index of a cursor is zero-based, so change:
游标的列索引从零开始,因此更改:
cursorState = c.getString(1);
cursorCapital = c.getString(2);
to
到
cursorState = c.getString(0);
cursorCapital = c.getString(1);