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))
}
}
To close the cursor, call the Cursor. close() method. Note that if you close a database that has cursors open in it, then it will throw an exception and close any open cursors for you. For best results, close your cursors from within a finally block.
The basic purpose of a cursor is to point to a single row of the result fetched by the query. We load the row pointed by the cursor object. By using cursor we can save lot of ram and memory.
Cursor is a Temporary Memory or Temporary Work Station. It is Allocated by Database Server at the Time of Performing DML(Data Manipulation Language) operations on Table by User. Cursors are used to store Database Tables. There are 2 types of Cursors: Implicit Cursors, and Explicit Cursors.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With