Make sure the Cursor is initialized correctly before accessing data from it

119 views Asked by At

I am new to android using kotlin.I am getting this error message in my log.

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.

My Code Look Like this.

 @SuppressLint("Range")
    fun getAllTask():ArrayList<TaskListModel>{
        val taskListModel =  ArrayList<TaskListModel>()
        val db = this.readableDatabase
        val selectQuery= "SELECT *FROM $TABLE_NAME"
        val cursor:Cursor?


        try{
            cursor = db.rawQuery(selectQuery,null)
        }catch (e: Exception){
            e.printStackTrace()
            db.execSQL(selectQuery)
            return ArrayList()
        }
            if (cursor.count > 0 && cursor.moveToFirst()){
                do {
                    val task = TaskListModel()
                    task.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID)))
                    task.name = cursor.getString(cursor.getColumnIndex(TABLE_NAME))
                    task.details = cursor.getString(cursor.getColumnIndex(TASK_DETAILS))
                    taskListModel.add(task)
                }while (cursor.moveToNext())
            }
        cursor.close()
        return  taskListModel
    }

enter image description here

1

There are 1 answers

8
Umang On

You have to check for cursor.count method. For example

if (cursor.count > 0 && cursor.moveToFirst())