diff --git a/src/androidTest/java/androidx/core/database/CursorTest.kt b/src/androidTest/java/androidx/core/database/CursorTest.kt index 86d07317..d1c65070 100644 --- a/src/androidTest/java/androidx/core/database/CursorTest.kt +++ b/src/androidTest/java/androidx/core/database/CursorTest.kt @@ -18,9 +18,7 @@ package androidx.core.database import android.database.Cursor import android.database.MatrixCursor -import org.junit.Assert.assertArrayEquals -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull +import org.junit.Assert.* import org.junit.Test class CursorTest { @@ -150,8 +148,36 @@ class CursorTest { assertNull(string) } + @Test fun isEmptyIsTrueWhenEmpty() { + val cursor = emptyCursor() + val isEmpty = cursor.isEmpty() + assertTrue(isEmpty) + } + + @Test fun isNotEmptyIsFalseWhenEmpty() { + val cursor = scalarCursor(1.5) + val isEmpty = cursor.isEmpty() + assertFalse(isEmpty) + } + + @Test fun isEmptyIsFalseWhenNotEmpty() { + val cursor = scalarCursor(1.5) + val isEmpty = cursor.isEmpty() + assertFalse(isEmpty) + } + + @Test fun isNotEmptyIsTrueWhenNotEmpty() { + val cursor = emptyCursor() + val isEmpty = cursor.isEmpty() + assertTrue(isEmpty) + } + private fun scalarCursor(item: Any?): Cursor = MatrixCursor(arrayOf("data")).apply { addRow(arrayOf(item)) moveToFirst() // Prepare for consumers to read. } + + private fun emptyCursor(): Cursor = MatrixCursor(arrayOf("data")).apply { + moveToFirst() // Prepare for consumers to read. + } } diff --git a/src/main/java/androidx/core/database/Cursor.kt b/src/main/java/androidx/core/database/Cursor.kt index b63e719f..e310109a 100644 --- a/src/main/java/androidx/core/database/Cursor.kt +++ b/src/main/java/androidx/core/database/Cursor.kt @@ -267,3 +267,17 @@ inline fun Cursor.getShortOrNull(columnName: String) = */ inline fun Cursor.getStringOrNull(columnName: String) = getColumnIndexOrThrow(columnName).let { if (isNull(it)) null else getString(it) } + +/** + * Returns true if the cursor has no entries, false otherwise. + */ +inline fun Cursor.isEmpty() = + count == 0 + +/** + * Returns true if the cursor has at least one entry, false otherwise. + */ +inline fun Cursor.isNotEmpty() = + count > 0 + +