MainActivity.kt
package com.example.coroutine
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.util.*
import kotlin.random.Random
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get room database instance
val db = RoomSingleton.getInstance(this)
// make text view text scrollable
textView.movementMethod = ScrollingMovementMethod()
btnInsert.setOnClickListener {
// generate a new student
val student = Student(
null,
UUID.randomUUID().toString(),
Random.nextInt(100)
)
// insert new student in room database
GlobalScope.launch(Dispatchers.IO) {
db.studentDao().insert(student)
}
}
btnSelect.setOnClickListener {
GlobalScope.launch(Dispatchers.IO) {
// get student list from room database using background thread
val list = db.studentDao().allStudents()
.sortedByDescending { it.id }
// dispatcher that is confined to the Main
// thread operating with UI objects
withContext(Dispatchers.Main){
textView.text = "Students(${list.count()})..."
// loop through the students list
list.forEach {
textView.append("\n${it.id} : ${it.fullName} : ${it.result}")
}
}
}
}
btnClear.setOnClickListener {
// dispatcher designed for offloading blocking
// IO tasks to a shared pool of threads
GlobalScope.launch(Dispatchers.IO) {
// delete all students from room student table
db.studentDao().clearStudents()
}
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F5F5F5"
tools:context=".MainActivity">
<com.google.android.material.button.MaterialButton
android:id="@+id/btnInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:backgroundTint="#0048BA"
android:text="Insert"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="@+id/btnSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:backgroundTint="#008000"
android:text="Select"
app:layout_constraintBottom_toBottomOf="@+id/btnInsert"
app:layout_constraintStart_toEndOf="@+id/btnInsert" />
<com.google.android.material.button.MaterialButton
android:id="@+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:backgroundTint="#E52B50"
android:text="Clear"
app:layout_constraintBottom_toBottomOf="@+id/btnSelect"
app:layout_constraintStart_toEndOf="@+id/btnSelect" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/textView"
style="@style/TextAppearance.MaterialComponents.Subtitle1"
android:layout_width="0dp"
android:layout_height="0dp"
android:textColor="#1B1811"
android:textStyle="bold"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnInsert"
app:layout_constraintVertical_bias="1.0"
tools:text="TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
RoomSingleton.kt
package com.example.coroutine
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import android.content.Context
@Database(entities = [Student::class], version = 1)
abstract class RoomSingleton : RoomDatabase() {
abstract fun studentDao():StudentDao
companion object {
private var INSTANCE: RoomSingleton? = null
fun getInstance(context: Context): RoomSingleton {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
context,
RoomSingleton::class.java,
"roomdb")
.build()
}
return INSTANCE as RoomSingleton
}
}
}
RoomDao.kt
package com.example.coroutine
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
@Dao
interface StudentDao{
@Query("SELECT * FROM studentTbl")
suspend fun allStudents():List<Student>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(student:Student)
@Query("DELETE FROM studentTbl")
suspend fun clearStudents()
}
RoomEntity.kt
package com.example.coroutine
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "studentTbl")
data class Student(
@PrimaryKey
var id:Long?,
@ColumnInfo(name = "uuid")
var fullName: String,
@ColumnInfo(name = "result")
var result:Int
)
build.gradle (app) [code to add]
apply plugin: 'kotlin-kapt'
dependencies {
// kotlin coroutine
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'
// room database
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
}
- android kotlin - RadioButton circle color programmatically
- android kotlin - Change checked RadioButton text color
- android kotlin - TextView margin programmatically
- android kotlin - Create TextView programmatically
- android kotlin - TextView add border programmatically
- android kotlin - Coroutines get html from url
- android kotlin - Coroutines JSON from URL
- android kotlin - Coroutines with LiveData
- android kotlin - Coroutines with ViewModel LiveData
- android kotlin - Coroutines Room ViewModel LiveData
- android kotlin - Coroutines async await all
- android kotlin - Coroutines cancel job
- android kotlin - Coroutines download image from url
- android kotlin - Coroutines url to bitmap
- android kotlin - Coroutines async