代码之家  ›  专栏  ›  技术社区  ›  zeeshan

使用关闭后,应释放此光标中的Kotlin

  •  0
  • zeeshan  · 技术社区  · 7 年前

    使用后如何正确关闭Kotlin中的光标。我知道如何用Java做这件事,但不管我在Kotlin做什么,它仍然警告关闭它。

    我试过:

            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()
                }
            }
    

    现代方式:

            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

    1 回复  |  直到 7 年前
        1
  •  3
  •   Andre Classen    7 年前
            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