Search code examples
androidcursor

SQLite cursor returning IllegalStateException?


I am trying to add elements to a DB and then search for a particular entry. But I get a cursor error. Here is my code for the DB class. The database contains only a single column. Thanks in advance.

public class DataB extends SQLiteOpenHelper {
    private static final String db_name = "testing.db";
    private static final int version = 1;
    private static final String table_name = "students";
    private static final String col_name="FirstName";
    public DataB(Context context) {
        super(context, db_name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String q = "CREATE TABLE " + table_name + " (FirstName TEXT PRIMARY KEY) ";
        db.execSQL(q);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+table_name);
        onCreate(db);
    }
    public int addData(String name)
    {
        ContentValues cv = new ContentValues();
        cv.put(col_name, name);
        SQLiteDatabase db = this.getWritableDatabase();
        db.insert(table_name, null, cv);
        db.close();
        return 1;
    }
    public String search(String string)
    {
        String dbstring=" ";
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM "+ table_name + " WHERE FirstName = '" + string+"'";
        Cursor c = db.rawQuery(query,null);
        c.moveToFirst();
        while(!c.isAfterLast())
        {
            if(c.getString(c.getColumnIndex("FirstName"))!=null)
            {
                dbstring = c.getString(c.getColumnIndex("FirstName"));
            }
        }
        return dbstring;
    }
}

The error is Caused by: java.lang.IllegalStateException: Couldn\'t read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.


Solution

  • The while is not working at all you are never changing the cursor position so it will always be true making a stackoverflow

    After performing your query you should ask if the cursor is not null and if can move to first position, like the following:

        if(c != null && c.moveToFirst()){      
           dbstring = c.getString(c.getColumnIndex(col_name));           
         }
    

    Or in your case because the only column you have is FirstName you can look it like this:

        if(c != null && c.moveToFirst()){      
           dbstring = c.getString(0);           
        }
    

    Remember that if you change anything in your database you should upgrade the database version.