Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 981
zeeshan Avatar asked Feb 01 '19 23:02

zeeshan


People also ask

How do you close a cursor in Kotlin?

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.

What is cursor in Kotlin?

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.

What is cursor class explain with example?

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.


1 Answers

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

like image 104
Andre Classen Avatar answered Oct 19 '22 19:10

Andre Classen