Kotlin This Cursor should be freed up after use with #close
Asked Answered
D

1

8

How to correctly close cursor in Kotlin after use. I know how to do it in Java but doesn't matter what I do in Kotlin, it still gives warning to close it.

I tried:

        val cursor = context!!.getContentResolver().query(DbProvider.CONTENT_URI_VERSES, null, where, null, null)!!
        if (cursor.moveToFirst()) {
            try {
                arabicTextTV.text = cursor.getString(cursor.getColumnIndex(DbHelper.COL_ARABIC1))
            } finally {
                cursor.close()
            }
        }

and the modern way:

        val cursor = context!!.getContentResolver().query(DbProvider.CONTENT_URI_VERSES, null, where, null, null)!!
        if (cursor.moveToFirst()) {
            cursor.use {
                arabicTextTV.text = cursor.getString(cursor.getColumnIndex(DbHelper.COL_ARABIC1))
            }
        }

enter image description here

enter image description here

Duplex answered 1/2, 2019 at 23:27 Comment(0)
T
15
context?.contentResolver?.query(DbProvider.CONTENT_URI_VERSES, null, where, null, null)?.use {
  if (it.moveToFirst()) {
    arabicTextTV.text = it.getString(it.getColumnIndex(DbHelper.COL_ARABIC1))
  }
}

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/use.html

Theater answered 1/2, 2019 at 23:40 Comment(2)
At least add a link to use documentation.Lollygag
Please put some explanation.Halloo

© 2022 - 2024 — McMap. All rights reserved.