0

Im trying to get the corresponding title to the given ID using the code below

public String get_Title(int id){
        Cursor c = db.query(true, DATABASE_TABLE, new String[] {
                APP_TITLE,
                },
                KEY_ROWID + "="  + id,
                null,
                null,
                null,
                null,
                null);

                String Final = c.getString(0);

                return Final;

        }

I keep gettting exceptions caused by the index out of bounds. IM not good with cursors, so if anyone could help me out here. :S

1 Answer 1

0

You must before String Final = c.getString(0) call c.moveToFirst() or c.moveToNext() and then it should works. Because Cursor is implicitly positioned to position before first row so you must at first move Cursor to first row and then you can get data from it.

EDIT:


So it should be like this:

if (c.getCount()) { // if there is some data
   c.moveToFirst();
   String Final = c.getString(0);
}
else {
   Toast.makeText(YourActivityName.this, "No data found", Toast.LENGTH_SHORT).show();
}

So you wrote that you not good in work with Cursor little introduction:

If you execute any statement, always instance of Cursor class will be returned. It's version of a database cursor, it is used in many database systems.

Class Cursor have following few basic methods:
  • getCount() - to get how many rows is in actual cursor
  • moveToFirst(), moveToNext() etc. - for moving between rows
  • getColumnNames() - to get column' names
  • getColumnIndex() - to get the zero-based index for the given column name...
  • getString(), getInt() etc. - to get data of requested column' index
  • requery() - once again execute cursor
  • close() - to release resources of cursor.
  • and next...

More about work with cursors you find here

Regards

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.