Kotlin android database: cannot cast java.lang.String to android.database.Cursor

719 views Asked by At

I'm developing a simple note app in Kotlin for Android which uses a simple sqlite database. I have already written it in java, but now I have some problems in Kotlin, in particular with a single line of code.

This is the working java code by which I take the note ID when I click on it on the listview.

itemCursor = (Cursor) activity.listView.getItemAtPosition(position);
noteID = itemCursor.getInt(itemCursor.getColumnIndex(DBHelper.NOTES_COLUMN_ID));
itemCursor = helper.getNote(noteID);

Then this should be the Kotlin code:

var itemCursor: Cursor = activity.listView.getItemAtPosition(position) as Cursor  **(error here on this line, look below for it)**
var noteID: Int = itemCursor.getInt(itemCursor.getColumnIndex(COLUMN_ID))
itemCursor = helper.getNote(noteID)

java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor

ListView adapter:

list_titles = helper.getAllTitles()
lv_adapter = ArrayAdapter(activity, android.R.layout.simple_list_item_1, list_titles)
v.listview.adapter = lv_adapter

getAllTitles fun:

fun getAllTitles(): ArrayList<String> {

    val db = this.readableDatabase
    var titles = ArrayList<String>()

    db.select(TABLE_NAME).parseList(object : MapRowParser<List<String>> {

        override fun parseRow(columns: Map<String, Any?>): ArrayList<String> {


            val obj = columns.getValue(COLUMN_OBJ).toString()

            titles.add(obj)

            return titles
        }
    })


    return titles

}

I do not understand why in Kotlin it gives me this ClassCastException error since in Java is all smooth.

1

There are 1 answers

1
Hohenheim On BEST ANSWER

Your fun getAllTitles(): ArrayList<String> it should be fun getAllTitles(): ArrayList<Cursor> if you want getItemAtPosition() to return a Cursor