Search code examples
androiddatabasesqlitecursor

What to do with Cursor after a SQLite query?


This is my first time using a database and I'm not really sure how this works. I made the database and made a query that returns a cursor and... now what? What is a cursor, really? Can I just use that to navigate through my data or do I have to put it in an ArrayList or ListActivity or what?


Solution

  • You need to iterate the cursor to get your results.

    Use cursor.moveToFirst() and/or cursor.moveToNext() (with a while loop). Then you can use the getX() method, like cursor.getInt() or cursor.getString().

    For example, ir your are expecting one result from your query:

    if (cursor.moveToFirst()) {
        String name = cursor.getString(cursor.getColumnIndex('NAME'));
        int age = cursor.getInt(cursor.getColumnIndex('AGE'));
    } else {
        // oops nothing found!
    }