android - Kotlin This Cursor 在使用#close 后应该被释放

标签 android kotlin android-cursor

使用后如何在 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

最佳答案

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

关于android - Kotlin This Cursor 在使用#close 后应该被释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54488454/

相关文章:

java - 如何访问 zip 文件中的 SQLite 数据库 - android

java - 文字超出相机范围

java - 如何为 Android 创建类似 iphone 的搜索

android - CursorLoaders 有什么好处?

android - 如何在 BroadcastReceiver 中知道 App 是否在前台运行?

kotlin - 为 Kotlin Swagger

java - 如何将上下文作为参数传递

android - 更新 Android 上通知 Intent 的额外数据?

android - 为什么我的游标返回 null?

java - 如何测试 SQLiteDatabase 查询中的光标是否为空