warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide
room.schemaLocation
annotation processor argument OR set exportSchema to false.
// build.gradle
android {
//...
defaultConfig {
//...
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
}
{
"formatVersion": 1,
"database": {
"version": 1,
"identityHash": "099390f8b7fbb65c66ec03eb92989ebb",
"entities": [
{
"tableName": "location_result",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider` TEXT NOT NULL, `latitude` REAL NOT NULL, `longitude` REAL NOT NULL, `accuracy` REAL NOT NULL, `create_date_time` TEXT NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "provider",
"columnName": "provider",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "latitude",
"columnName": "latitude",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "longitude",
"columnName": "longitude",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "accuracy",
"columnName": "accuracy",
"affinity": "REAL",
"notNull": true
},
{
"fieldPath": "createDateTime",
"columnName": "create_date_time",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": true
},
"indices": [],
"foreignKeys": []
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"099390f8b7fbb65c66ec03eb92989ebb\")"
]
}
}
@Database(entities = arrayOf(LocationResult::class), version = 1, exportSchema = false)
abstract class Database : RoomDatabase() {
//...
}
// kotlin annotation processing tool
apply plugin: 'kotlin-kapt'
dependencies {
implementation 'android.arch.persistence.room:runtime:1.0.0-rc1'
kapt 'android.arch.persistence.room:compiler:1.0.0-rc1'
}
@Entity(tableName = "location_result")
data class LocationResult (
val provider : String,
val latitude : Double,
val longitude : Double,
val accuracy : Double,
@ColumnInfo(name = "create_date_time")
val createDateTime : String) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
}
@Dao
interface LocationResultDao {
@Query("SELECT * FROM location_result")
fun findAll(): List<LocationResult>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun create(locationResult: LocationResult)
@Update
fun update(locationResult: LocationResult)
@Delete
fun delete(locaionResult: LocationResult)
}
@Database(entities = arrayOf(LocationResult::class), version = 1, exportSchema = false)
abstract class Database : RoomDatabase() {
abstract fun locationResultDao(): LocationResultDao
}
class ApplicationImpl : Application() {
companion object {
private lateinit var INSTANCE: ApplicationImpl
fun getInstance() = INSTANCE
lateinit var database: Database
}
override fun onCreate() {
super.onCreate()
INSTANCE = this
database = Room.databaseBuilder(this, Database::class.java, "location-result-db").build()
}
}
async {
ApplicationImpl.database.locationResultDao().create(LocationResult("Fused", location.latitude, location.longitude, 0.0, getCurrentDateTime()))
}
async {
val result = ApplicationImpl.database.locationResultDao().findAll()
Log.d("LocationSample", result.toString())
}
아래와 같이 사용하던 코드를…
var SECOND = 10 * 1000
var MINUTE = SECOND * 60
...
val SECOND = 1.seconds
val fiveMinutes = 5.minutes
// 아래와 같이 연산자도 사용 가능하다.
val tempSeconds = 10.seconds + 3.minutes
// 변환도 가능하다.
val fourDaysInHours = 4.days.inHours
// 비교도 된다.
50.seconds < 2.hours // true
120.minutes == 2.hours // true
100.milliseconds > 2.seconds // false
48.hours in 2.days // true
// 필요한건 만들어 써도 된다.
class Week : TimeUnit {
// number of seconds in one week
override val timeIntervalRatio = 604800.0
}
val fiveWeeks = Interval<Week>(5)
...
// Calendar 와 Thread, Android Handler를 위해 몇몇 함수를 확장해두었다.
fun main(args: Array<String>) {
println("Hello, world!")
}
위 코드로 알 수 있는 것들…
함수의 리턴 타입은 어디에 써야하나..?
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}
>>> println(max(1, 2))
2
Statements and Expression
exression(표현식) : 값이 있는 코드, 값을 반환하는 코드, 다른 표현식의 부분으로 사용될 수 있다. side-effect가 없다.
statement(문장, 구문) : 실행되는 코드 단위, 그 자체로 값을 가지지 않는다. side-effectr가 있을 수도 있다.
코틀린에서 if는 표현식이다.
java에서 assignment(할당)은 expression이지만 코틀린에서는 statement다.
fun max(a: Int, b: Int) = if(a > b) a else b
자바에서 변수 선언은 타입이 먼저 온다. 코틀린에서는 대부분의 타입 선언을 생략할 수 있기 때문에 타입 선언은 뒤에 온다.
val question =
"The Ultimate Question of Life, the Universe, and Everything"
val answer = 42
val answer: Int = 42 // 타입을 명시적으로 쓸 수도 있다.
val yearsToCompute = 7.6e6 // Double형
val answer: Int // 초기화 되지 않는 경우 타입을 명시적으로 써줘야 한다.
answer = 42
변수를 선언할때는 아래의 2개 키워드를 사용한다.
기본적으로, 변수 선언은 val로 하고 꼭 필요한 경우에만 var로 선언한다. 불변 변수, 객체, 함수를 사용하는 것은 함수형 스타일로 side-effect를 최소화 할 수 있다.
원본 글 : https://academy.realm.io/posts/360-andev-2017-mercedes-wyss-java-8-features-android/
아래 내용들이 나오나, 짧은 시간인 만큼 간단한 소개이다.
결론은.. 코틀린을 써라 인가. -_-;;