Skip to content
This repository has been archived by the owner on Nov 14, 2018. It is now read-only.

Add empty check functions #573

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions src/androidTest/java/androidx/core/database/CursorTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
}
}
14 changes: 14 additions & 0 deletions src/main/java/androidx/core/database/Cursor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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