Kotlin This Cursor 在使用#close 后应该被释放
Kotlin This Cursor should be freed up after use with #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
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