コトリンDB


DBの使用
-アプリケーションランプの追加
plugins {
	id 'com.android.application'
	id 'kotlin-android'
	id 'kotlin-kapt'
}


라이브러리(defendencies)
	kapt "androidx.room:room-compiler:2.2.6"     
	implementation "androidx.room:room-runtime:2.2.6"
-DBソリッドモデル(テーブル)宣言
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity
data class History(
	@PrimaryKey val uid: Int?,
	@ColumnInfo(name = "expression") val expression: String?,
	@ColumnInfo(name = "result") val result: String?
)
-テーブルの操作方法(インタフェース)を定義します.
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import fastcampus.aop.part2.chapter4.model.History

@Dao
interface HistoryDao {
	@Query("SELECT * FROM history")
	fun getAll(): List<History>

	@Insert
	fun insertHistory(history: History)

	@Query("DELETE FROM history")
	fun deleteAll()

	@Delete
	fun delete(history: History)
	
	@Query("SELECT * FROM history Where result LIKE :result LIMIT 1")
	fun findByResult(result: String):History
}
-抽象クラスを作成して実際のクラスで使用
import androidx.room.Database
import androidx.room.RoomDatabase
import fastcampus.aop.part2.chapter4.dao.HistoryDao
import fastcampus.aop.part2.chapter4.model.History

@Database(entities = [History::class], version = 1)
	abstract class AppDatabase : RoomDatabase() {
	abstract fun historyDao(): HistoryDao
}
-使用
선언
	lateinit var db: AppDatabase

onCreate
	db = Room.databaseBuilder(
		applicationContext,
		AppDatabase::class.java,
		"historyDB"
		).build()

DB 조작  
	Thread(Runnable {
    		db.historyDao().insertHistory(History(null, expressionText, resultText))
	}).start()
      
      
	Thread(Runnable {
		db.historyDao().getAll().reversed().forEach {
		runOnUiThread {
			val historyView = LayoutInflater.from(this).inflate(R.layout.history_row, null, false)
			historyView.findViewById<TextView>(R.id.expressionTextView).text = it.expression
			historyView.findViewById<TextView>(R.id.resultTextView).text = "= ${it.result}"
			historyLinearLayout.addView(historyView)
			}
		}
	}).start()