android - Kotlin 这个游标应该在使用 #close 后被释放
问题描述
使用后如何正确关闭 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))
}
}
解决方案
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
推荐阅读
- r - 在 R 中大写有例外
- c# - 在这种情况下使用 get key down 的正确方法是什么?
- django - 无法填充 django3 数据库
- php - 更改“返回商店”以返回上一页
- python - Quantopian 实时算法 - 如何?
- c - 用于删除 xx:xx:xx:xx:xx:xx 的 C 字符串操作
- python - Pandas 多索引 DataFrame 到 JSON
- javascript - D3.js 缩放:热图的离散比例不更新
- c# - 从 Bootstrap 模式弹出窗口提交数据
- ruby-on-rails - 尝试从 API 获取 JSON 数据时出现 No such file or directory 错误?