简体   繁体   中英

Error when accessing cursor elements

I'm trying to get all the IDs in the table by cursor. The table has 4 rows, and when I try to access the cursor by any index aside from 0 , the App crashes.

Guys, the problem still exists and even c.getInt(0) doesn't work...I really dont know where my mistake is???

the logcat also suggests that the error might be comes from

Toast.makeText(getApplicationContext(), "id="+dbd.getIDs()[0], Toast.LENGTH_SHORT).show();

I mean c.getint(0) returns the id, c.getint(2) returns error. Here is the code:

public int []getIDs() {
    SQLiteDatabase db = this.getReadableDatabase();
    SQLiteCursor c = (SQLiteCursor) db.rawQuery("SELECT " + BaseColumns._ID + " FROM Demo ", null);

    int []r = new int[c.getCount()];
    c.moveToFirst();

    do{
        r[c.getPosition()] = c.getInt(0); 
    }while(c.moveToNext());

    c.close();
    db.close();
    return r;       
}

Your select is a projection onto the ID column (select columns from ..., columns are the column ids you are interested in, and you specified just one). Thus the answer just has one column, namely the ID. Any access to columns with index > 0 will not work.

To access the other columns name them in the projection in your query.

c.getInt(0) return only value of first colunn from current row.

try this code:

do{
int r = c.getInt(0);
Log.d("Your class name","id value = "+r);
}while(c.moveToNext());

You can imagine Cursor as a table. There are rows and columns. And a cursor is pointing on a particular row in this table. Thus, to get all id's you should move across all rows.

c.getInt(ind) In this statement index is pointing on the column with index ind. Thus, in your code you try to get the second and third column and according to your code there is no these column.

To get a proper code you should create a loop and traverse all rows of your cursor. Also you should use c.getInt(0) to get the columns values.

Assuming you are selecting the appropriate Data, your problem is that you're not preparing the Cursor to be iterated.

Before iterating, call:

c.moveToFirst();

Like this:

int []r = new int [c.getCount()];
c.moveToFirst();
    do{
        r[c.getPosition()] = c.getInt(0);
    }while(c.moveToNext());

    c.close();
    db.close();
    return r;   

This is well indicated in LogCat. I can't remember how it's put, but the message is very suggestive. Please post as much of the Log as possible, especially the good bits.

Also, I modified 'r' to be an array. As it was you were only returning the value of the last row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM