Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handle cursor by delegates
inline fun <T> Cursor.delegate(key: String? = null,
crossinline getter: Cursor.(Int) -> T): ReadOnlyProperty<Any?, T> {
return object : ReadOnlyProperty<Any?, T> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
val s = key ?: property.name
return getter(getColumnIndex(s))
}
}
}
fun Cursor.int(key: String? = null) = delegate(key = key, getter = Cursor::getInt)
fun Cursor.string(key: String? = null) = delegate(key = key, getter = Cursor::getString)
fun Cursor.boolean(key: String? = null) = delegate(key = key, getter = Cursor::getBoolean)
fun Cursor.double(key: String? = null) = delegate(key = key, getter = Cursor::getDouble)
fun Cursor.long(key: String? = null) = delegate(key = key, getter = Cursor::getLong)
fun Cursor.byteArray(key: String? = null) = delegate(key = key, getter = Cursor::getBlob)
fun Cursor.float(key: String? = null) = delegate(key = key, getter = Cursor::getFloat)
fun Cursor.short(key: String? = null) = delegate(key = key, getter = Cursor::getShort)
fun Cursor.getBoolean(columnIndex:Int): Boolean = getInt(columnIndex)!=0
//Additional method to reduce boilerplate
fun Cursor?.readCursor(cursorReadFun: (Cursor) -> Unit) {
this?.let {
moveToFirst()
do {
cursorReadFun(it)
} while (moveToNext())
}
}
//Full Example
cursor.readCursor{
val doubleProperty by cursor.double("doubleProperty")
val intProperty by cursor.int("intProperty")
val stringProperty by cursor.string("stringProperty")
val booleanProperty by cursor.boolean("booleanProperty")
}
@Zhuinden

This comment has been minimized.

Copy link

@Zhuinden Zhuinden commented May 21, 2018

I think fun Cursor?.readCursor should be inline

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment