Skip to content

Instantly share code, notes, and snippets.

@jacobmoncur
Last active July 19, 2017 17:07
Show Gist options
  • Save jacobmoncur/1b5b55a4cd0fc3938d1c53480f833b72 to your computer and use it in GitHub Desktop.
Save jacobmoncur/1b5b55a4cd0fc3938d1c53480f833b72 to your computer and use it in GitHub Desktop.
Sample of Room using Kotlin.
class App: Application() {
companion object {
lateinit var database: MyDatabase
}
override fun onCreate() {
super.onCreate()
App.database = Room.databaseBuilder(this, MyDatabase::class.java, "my-database").build()
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
AsyncTask.execute {
val operation = Operation(0, 4.5f, 4.5f, "+", 9.0f)
App.database.operationDao().insert(operation)
val operations = App.database.operationDao().getAllOperations()
val arrayList = ArrayList<String>()
operations.forEach { operation ->
arrayList.add(operation.expression())
}
println(arrayList)
}
}
}
@Database(entities = arrayOf(Operation::class), version = 0)
abstract class MyDatabase : RoomDatabase() {
abstract fun operationDao(): OperationDao
}
@Dao
interface OperationDao {
@Query("SELECT * FROM operation")
fun getAllOperations(): List<Operation>
@Insert
fun insert(operation: Operation)
}
@Entity
data class Operation(
@PrimaryKey(autoGenerate = true)
val uid: Long,
val firstNumber: Float = 0.0f,
val secondNumber: Float = 0.0f,
val operator: String = "",
val result: Float = 0.0f
)
fun Operation.expression(): String = "$firstNumber $operator $secondNumber = $result"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment