Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

java - Error: Make sure the Cursor is initialized correctly before accessing data from it?

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...