Skip to content

Instantly share code, notes, and snippets.

@PrashamTrivedi
Created January 23, 2018 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PrashamTrivedi/ed02e991a1340ee2d5fcaf38a7981658 to your computer and use it in GitHub Desktop.
Save PrashamTrivedi/ed02e991a1340ee2d5fcaf38a7981658 to your computer and use it in GitHub Desktop.
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
Copy link

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