Search code examples
androidsqlitecursor

SQLiteQuery returns null cursor


I have the following database, which I've checked it has few records (is not empty). There is something wrong with my selectLink() method, because it returns null cursor (the idea was it should return a row of the given "_id".

Table creation:

private static final String DATABASE_CREATE = "create table HttpLinks ( _id integer primary key AUTOINCREMENT,name text not null);";

Row retrieve:

public final static String ID="_id";
public final static String NAME="name"

public String selectLink(long id)   {
    String[] cols  = new String[] {NAME};
    Cursor mCursor = database.query(TABLE, cols, ID+"="+String.valueOf(id),null,null,null,null,null);
return mCursor.getString(0);

logcat error:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
    android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

Solution

  • the query does not return null clearly as you dont get a NullPointerException you get a CursorIndexOutOfBoundsException because you are not calling moveToFirst before you use the cursor

    right before this line

    return mCursor.getString(0);
    

    you need to do

    mCursor.moveToFirst();