본문 바로가기
프로그래밍

제네릭을 이용하니 SQLite 데이터 읽고 쓰기 편하네

by hansoo.labs 한수댁 2018. 1. 29.

Read and Write in SQLite using kotlin generic

코틀린의 타입 케스팅과 제너릭함수를 이용하니 편하군..



private fun <T> setValue(uid: Long, key: String, value: T) {
    var id: Long = -2
    val cursor = getCursor(uid)
    if (cursor != null && cursor.moveToFirst()) {
        val contentValues = ContentValues()
        when(value) {
            is Int -> { contentValues.put(key, value) }
            is String -> { contentValues.put(key, value)}
            is Boolean -> { contentValues.put(key, value)}
            is Long -> { contentValues.put(key, value)}
            is Float -> { contentValues.put(key, value)}
            is Double ->  { contentValues.put(key, value)}
            is Byte -> { contentValues.put(key, value)}
            is ByteArray -> { contentValues.put(key, value)}
        }
        id = brite.update(TABLE_NAME, SQLiteDatabase.CONFLICT_REPLACE, contentValues,
            KEY_ID + "=?", uid.toString()).toLong()
    }
    cursor?.close()
}

@Suppress("UNCHECKED_CAST")
private fun <T> getValue(uid: Long, key: String, defValue: Any): T {
    var value = defValue
    val cursor = getCursor(uid)
    if (cursor != null && cursor.moveToFirst()) {
        when(value) {
            is Int -> value = cursor.getInt(cursor.getColumnIndex(key))
            is String -> value = cursor.getString(cursor.getColumnIndex(key))
            is Boolean -> { value = cursor.getInt(cursor.getColumnIndex(key)) > 0 }
            is Long -> { value = cursor.getLong(cursor.getColumnIndex(key))}
            is Float -> { value = cursor.getFloat(cursor.getColumnIndex(key)) }
            is Double -> { value = cursor.getDouble(cursor.getColumnIndex(key)) }
            is Byte -> { value = cursor.getShort(cursor.getColumnIndex(key)) }
            is ByteArray -> { value = cursor.getBlob(cursor.getColumnIndex(key)) }
        }
    }
    cursor?.close()
    return value as T
}


값을 읽을 때는 기본값을 통해서 타입을 측정하기 때문에 Boolean 값은 이렇게 읽어야 함.

val value: Boolean = (getValue(key, "컬럼이름", 0) as Int) == 1

하하;;

댓글0