android kotlin - Room LIKE query example

MainActivity.kt

package com.example.roomexamples

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.toast
import org.jetbrains.anko.uiThread


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val room = RoomSingleton.getInstance(this)
        textView.movementMethod = ScrollingMovementMethod()

        // Insert some products in database
        btnInsert.setOnClickListener {
            it.isEnabled = false
            val url = "https://pastebin.com/raw/BrQjM5dX"

            val request = JsonArrayRequest(
                Request.Method.GET,
                url,
                null,
                Response.Listener{
                    val list = arrayListOf<Employee>()

                    for (i in 0 until it.length()){
                        val obj = it.getJSONObject(i)

                        val name = obj.getString("name")
                        val salary = obj.getLong("salary")
                        val age = obj.getInt("age")

                        val emp = Employee(null,name,salary,age)
                        list.add(emp)

                    }

                    doAsync {
                        room.empDao().insertAll(list)

                        uiThread {
                            toast("done")
                        }
                    }

                },Response.ErrorListener {
                    toast(it.toString())
                }
            )

            // Add the request to the RequestQueue.
            Volley.newRequestQueue(this).add(request)
        }

        btn1.setOnClickListener {
            doAsync {
                val list = room.empDao().empLIKEtha()

                uiThread {
                    textView.text = ""
                    list.forEach{
                        textView.append("" + it.id + ". ")
                        textView.append(it.name)
                        textView.append(" Age: " + it.age)
                        textView.append(" Salary: " + it.salary + "\n")
                    }
                }
            }
        }

        btn2.setOnClickListener {
            doAsync {
                // You need to enclose the % characters in input query
                val list = room.empDao().empByLike("%al%")

                // Or
                //val list = room.empDao().empByLike("%al")

                // Or
                //val list = room.empDao().empByLike("al%")

                uiThread {
                    textView.text = ""
                    list.forEach{
                        textView.append("" + it.id + ". ")
                        textView.append(it.name)
                        textView.append(" Age: " + it.age)
                        textView.append(" Salary: " + it.salary + "\n")
                    }
                }
            }
        }
    }
}
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"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="8dp"
        android:text=""
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnInsert"
        />
    <Button
        android:id="@+id/btnInsert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Insert"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="LIKE %tha%"
        app:layout_constraintStart_toEndOf="@+id/btnInsert"
        app:layout_constraintTop_toTopOf="parent"
        android:textAllCaps="false"
        />
    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Like %al%"
        app:layout_constraintStart_toEndOf="@+id/btn1"
        app:layout_constraintTop_toTopOf="parent"
        android:textAllCaps="false"
        />
</androidx.constraintlayout.widget.ConstraintLayout>
RoomSingleton.kt

package com.example.roomexamples

import android.content.Context
import androidx.room.*

@Database(entities = arrayOf(Employee::class), version = 1, exportSchema = false)

abstract class RoomSingleton : RoomDatabase(){
    abstract fun empDao(): EmpDao
    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.roomexamples

import androidx.room.*


@Entity(tableName = "empTbl")
data class Employee(
    @PrimaryKey(autoGenerate = true)
    var id:Int?=null,
    var name:String,
    var salary:Long,
    var age:Int
)

@Dao
interface EmpDao{
    @Query("SELECT * FROM empTbl")
    fun allEmployee():List<Employee>

    @Query("SELECT * FROM empTbl WHERE name LIKE '%tha%'")
    fun empLIKEtha():List<Employee>

    @Query("SELECT * FROM empTbl WHERE name LIKE:searchText")
    fun empByLike(searchText:String):List<Employee>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(emp:Employee)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(list:List<Employee>)
}
app build.gradle [required]

apply plugin: 'kotlin-kapt'

dependencies {
    // Room
    def room_version = "2.2.0-alpha01"
    implementation "androidx.room:room-runtime:$room_version"
    kapt 'androidx.room:room-compiler:2.2.0-alpha01'

    // Anko Commons
    implementation "org.jetbrains.anko:anko-commons:0.10.8"

    // Volley network library
    implementation 'com.android.volley:volley:1.1.1'
}

android kotlin - Room boolean column example

MainActivity.kt

package com.example.roomexamples

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.toast
import org.jetbrains.anko.uiThread
import java.text.DateFormat
import java.util.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val room = RoomSingleton.getInstance(this)
        textView.movementMethod = ScrollingMovementMethod()

        // Insert some products in database
        btnInsert.setOnClickListener {
            val url = "https://tradeogre.com/api/v1/history/BTC-KRB"

            val request = JsonArrayRequest(
                Request.Method.GET,
                url,
                null,
                Response.Listener{
                    val list = arrayListOf<History>()

                    for (i in 0 until it.length()){
                        val obj =  it.getJSONObject(i)

                        val timeMillis = obj.getLong("date")
                        val type = obj.getString("type")
                        val price = obj.getString("price").toBigDecimal()
                        val quantity = obj.getString("quantity").toBigDecimal()

                        var isSell = true
                        if (type.equals("buy")) isSell = false

                        val history = History(null,Date(timeMillis),isSell,price,quantity)
                        list.add(history)
                    }

                    doAsync {
                        room.historyDao().insertAll(list)
                        uiThread {
                            toast("done")
                        }
                    }


                },Response.ErrorListener {
                    toast(it.toString())
                }
            )

            // Add the request to the RequestQueue.
            Volley.newRequestQueue(this).add(request)
        }

        btnSell.setOnClickListener {
            doAsync {
                val list = room.historyDao().allSale()

                uiThread {
                    displayResult(list,textView)
                }
            }
        }


        btnBuy.setOnClickListener {
            doAsync {
                // Pass boolean parameter to room query
                val list = room.historyDao().allByQuery(false)

                uiThread {
                    displayResult(list,textView)
                }
            }
        }
    }
}


fun displayResult(list:List<History>,textView:TextView){
    textView.text = ""
    list.forEach {
        textView.append(it.date.medium)
        if (it.isSell){
            textView.append("\nType: Sell")

        }else{
            textView.append("\nType: Buy")
        }
        textView.append("\nPrice: " + it.price)
        textView.append("\nQuantity: " + it.quantity + "\n\n")
    }
}


// Extension property to format date
val Date.medium:String
    get() = DateFormat.getDateInstance(DateFormat.MEDIUM).format(this)
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"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="8dp"
        android:text=""
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnInsert"
        />
    <Button
        android:id="@+id/btnInsert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Insert"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
    <Button
        android:id="@+id/btnSell"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Sell"
        app:layout_constraintStart_toEndOf="@+id/btnInsert"
        app:layout_constraintTop_toTopOf="parent" 
        />
    <Button
        android:id="@+id/btnBuy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Buy"
        app:layout_constraintStart_toEndOf="@+id/btnSell"
        app:layout_constraintTop_toTopOf="parent"
        />
</androidx.constraintlayout.widget.ConstraintLayout>
RoomSingleton.kt

package com.example.roomexamples

import android.content.Context
import androidx.room.*

@Database(entities = arrayOf(History::class), version = 1, exportSchema = false)
@TypeConverters(Converter::class)

abstract class RoomSingleton : RoomDatabase(){
    abstract fun historyDao(): HistoryDao
    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.roomexamples

import androidx.room.*
import java.math.BigDecimal
import java.util.*


@Entity(tableName = "historyTbl")
data class History(
    @PrimaryKey(autoGenerate = true)
    var id:Long?=null,
    var date:Date,
    var isSell:Boolean,
    var price:BigDecimal,
    var quantity:BigDecimal
)


@Dao
interface HistoryDao {

    // SQLite have no boolean data type
    // Room maps boolean data to an INTEGER column
    // Room mapping true to 1 and false to 0
    @Query("SELECT * FROM historyTbl WHERE isSell = 1 ORDER BY date DESC")
    fun allSale():List<History>

    @Query("SELECT * FROM historyTbl WHERE isSell =:isSell ORDER BY date DESC")
    fun allByQuery(isSell: Boolean):List<History>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(history:History)

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insertAll(histories:List<History>)
}
Converter.kt

package com.example.roomexamples

import androidx.room.TypeConverter
import java.math.BigDecimal
import java.util.*

class Converter{
    companion object{
        @TypeConverter
        @JvmStatic
        fun fromBigDecimal(value:BigDecimal):String{
            return value.toString()
        }

        @TypeConverter
        @JvmStatic
        fun toBigDecimal(value:String):BigDecimal{
            return value.toBigDecimal()
        }

        @TypeConverter
        @JvmStatic
        fun toDate(value:Long):Date{
            //If your result always returns 1970, then comment this line
            //val date =  Date(value)

            //If your result always returns 1970, then uncomment this line
            val date = Date(value*1000L)

            return date
        }

        @TypeConverter
        @JvmStatic
        fun fromDate(date:Date):Long{
            return date.time
        }
    }
}
app build.gradle [required]

apply plugin: 'kotlin-kapt'

dependencies {
    // Room
    def room_version = "2.2.0-alpha01"
    implementation "androidx.room:room-runtime:$room_version"
    kapt 'androidx.room:room-compiler:2.2.0-alpha01'

    // Anko Commons
    implementation "org.jetbrains.anko:anko-commons:0.10.8"

    // Volley network library
    implementation 'com.android.volley:volley:1.1.1'
}

android kotlin - Room TypeConverter date example

MainActivity.kt

package com.example.roomexamples

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.toast
import org.jetbrains.anko.uiThread
import java.text.DateFormat
import java.util.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val room = RoomSingleton.getInstance(this)
        textView.movementMethod = ScrollingMovementMethod()


        // Insert some products in database
        btnInsert.setOnClickListener {
            val url = "https://tradeogre.com/api/v1/history/BTC-KRB"

            val request = JsonArrayRequest(
                Request.Method.GET,
                url,
                null,
                Response.Listener{
                    val list = arrayListOf<History>()

                    for (i in 0 until it.length()){
                        val obj =  it.getJSONObject(i)

                        val timeMillis = obj.getLong("date")
                        val type = obj.getString("type")
                        val price = obj.getString("price").toBigDecimal()
                        val quantity = obj.getString("quantity").toBigDecimal()

                        val history = History(null,Date(timeMillis),type,price,quantity)
                        list.add(history)
                    }

                    doAsync {
                        room.historyDao().insertAll(list)
                        uiThread {
                            toast("done")
                        }
                    }


                },Response.ErrorListener {
                    toast(it.toString())
                }
            )

            // Add the request to the RequestQueue.
            Volley.newRequestQueue(this).add(request)
        }

        btnSelect.setOnClickListener {
            doAsync {
                val list = room.historyDao().allHistory()

                uiThread {
                    textView.text = ""
                    list.forEach {
                        textView.append(it.date.medium)
                        textView.append("\nType: " + it.type)
                        textView.append("\nPrice: " + it.price)
                        textView.append("\nQuantity: " + it.quantity + "\n\n")
                    }
                }
            }
        }
    }
}


// Extension property to format date
val Date.medium:String
get() = DateFormat.getDateInstance(DateFormat.MEDIUM).format(this)
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"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="8dp"
        android:text=""
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnInsert" />
    <Button
        android:id="@+id/btnInsert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Insert"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
    <Button
        android:id="@+id/btnSelect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Select"
        app:layout_constraintStart_toEndOf="@+id/btnInsert"
        app:layout_constraintTop_toTopOf="parent"
        />
</androidx.constraintlayout.widget.ConstraintLayout>
RoomSingleton.kt

package com.example.roomexamples

import android.content.Context
import androidx.room.*

@Database(entities = arrayOf(History::class), version = 1, exportSchema = false)
@TypeConverters(Converter::class)

abstract class RoomSingleton : RoomDatabase(){
    abstract fun historyDao(): HistoryDao
    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.roomexamples

import androidx.room.*
import java.math.BigDecimal
import java.util.*


@Entity(tableName = "historyTbl")
data class History(
    @PrimaryKey(autoGenerate = true)
    var id:Long?=null,
    var date:Date,
    var type:String,
    var price:BigDecimal,
    var quantity:BigDecimal
)


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

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(history:History)

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insertAll(histories:List<History>)
}
Converter.kt

package com.example.roomexamples

import androidx.room.TypeConverter
import java.math.BigDecimal
import java.util.*

class Converter{
    companion object{
        @TypeConverter
        @JvmStatic
        fun fromBigDecimal(value:BigDecimal):String{
            return value.toString()
        }

        @TypeConverter
        @JvmStatic
        fun toBigDecimal(value:String):BigDecimal{
            return value.toBigDecimal()
        }

        @TypeConverter
        @JvmStatic
        fun toDate(value:Long):Date{
            //If your result always returns 1970, then comment this line
            //val date =  Date(value)

            //If your result always returns 1970, then uncomment this line
            val date = Date(value*1000L)

            return date
        }

        @TypeConverter
        @JvmStatic
        fun fromDate(date:Date):Long{
            return date.time
        }
    }
}
app build.gradle [required]

apply plugin: 'kotlin-kapt'

dependencies {
    // Room
    def room_version = "2.2.0-alpha01"
    implementation "androidx.room:room-runtime:$room_version"
    kapt 'androidx.room:room-compiler:2.2.0-alpha01'

    // Anko Commons
    implementation "org.jetbrains.anko:anko-commons:0.10.8"

    // Volley network library
    implementation 'com.android.volley:volley:1.1.1'
}

android kotlin - Room TypeConverter example

MainActivity.kt

package com.example.roomexamples

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.toast
import org.jetbrains.anko.uiThread


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val room = RoomSingleton.getInstance(this)
        textView.movementMethod = ScrollingMovementMethod()

        // Insert some products in database
        btnInsert.setOnClickListener {
            val url = "https://tradeogre.com/api/v1/markets"

            val request = JsonArrayRequest(
                Request.Method.GET,
                url,
                null,
                Response.Listener{
                    val list = arrayListOf<Product>()

                    for (i in 0 until it.length()){
                        val obj =  it.getJSONObject(i)
                        val name = obj.names()[0].toString()
                        val values = obj.getJSONObject(name)

                        val initialPrice = values.getString("initialprice").toBigDecimal()
                        val price = values.getString("price").toBigDecimal()

                        val product = Product(name,initialPrice,price)
                        list.add(product)
                    }

                    doAsync {
                        room.productDao().insertAll(list)
                        uiThread {
                            toast("done")
                        }
                    }


                },Response.ErrorListener {
                    toast(it.toString())
                }
            )

            // Add the request to the RequestQueue.
            Volley.newRequestQueue(this).add(request)
        }

        btnSelect.setOnClickListener {
            doAsync {
                val products = room.productDao().priceChange()

                uiThread {
                    textView.text = ""
                    products.forEach {
                        textView.append(it.name)
                        textView.append("\nInitial Price: " + it.initialPrice.toPlainString())
                        textView.append("\nPrice: " + it.price.toPlainString())
                        textView.append("\nChange: " + it.change.toPlainString() + "\n\n")
                    }
                }
            }
        }
    }
}
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"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="8dp"
        android:text=""
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnInsert" />
    <Button
        android:id="@+id/btnInsert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Insert"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
    <Button
        android:id="@+id/btnSelect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Select"
        app:layout_constraintStart_toEndOf="@+id/btnInsert"
        app:layout_constraintTop_toTopOf="parent"
        />
</androidx.constraintlayout.widget.ConstraintLayout>
RoomSingleton.kt

package com.example.roomexamples

import android.content.Context
import androidx.room.*

@Database(entities = arrayOf(Product::class), version = 1, exportSchema = false)
@TypeConverters(Converter::class)

abstract class RoomSingleton : RoomDatabase(){
    abstract fun productDao(): ProductDao
    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.roomexamples

import androidx.room.*
import java.math.BigDecimal


@Entity(tableName = "productTbl")
data class Product(
    @PrimaryKey
    var name:String,
    var initialPrice: BigDecimal,
    var price:BigDecimal
)

data class PriceChange(
    var name: String,
    var initialPrice: BigDecimal,
    var price: BigDecimal,
    var change:BigDecimal
)


@Dao
interface ProductDao {
    @Query("SELECT * FROM productTbl")
    fun allProducts():List<Product>

    @Query("SELECT *, price-initialPrice as change FROM productTbl")
    fun priceChange():List<PriceChange>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(product:Product)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(products:List<Product>)
}
Converter.kt

package com.example.roomexamples

import androidx.room.TypeConverter
import java.math.BigDecimal

class Converter{
    companion object{
        @TypeConverter
        @JvmStatic
        fun fromBigDecimal(value:BigDecimal):String{
            return value.toString()
        }

        @TypeConverter
        @JvmStatic
        fun toBigDecimal(value:String):BigDecimal{
            return value.toBigDecimal()
        }
    }
}
app build.gradle [required]

apply plugin: 'kotlin-kapt'

dependencies {
    // Room
    def room_version = "2.2.0-alpha01"
    implementation "androidx.room:room-runtime:$room_version"
    kapt 'androidx.room:room-compiler:2.2.0-alpha01'

    // Anko Commons
    implementation "org.jetbrains.anko:anko-commons:0.10.8"

    // Volley network library
    implementation 'com.android.volley:volley:1.1.1'
}

android kotlin - Room select where example

MainActivity.kt

package com.example.roomexamples

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val room = RoomSingleton.getInstance(this)
        textView.movementMethod = ScrollingMovementMethod()

        // Insert some books in database
        btnInsert.setOnClickListener {
            doAsync {
                room.bookDao().insertBooks(bookList())
            }
        }

        // Select books from database
        btnSelect.setOnClickListener {
            doAsync {
                // Get books which price greater than $50
                val books = room.bookDao().allBooks(50F)

                uiThread {
                    textView.text = ""
                    books.forEach {
                        textView.append(it.name + "\nPrice: $" + it.price + "\n\n")
                    }
                }
            }
        }
    }
}


fun bookList():List<Book>{
    return listOf(
        Book(
            "978-1-119-44927-0",
            "Professional C# 7 and .NET Core 2.0",
            "Christian Nagel",
            60F
        ),
        Book(
            "978-1-118-94952-8",
            "Professional Android, 4th Edition",
            "Reto Meier, Ian Lake",
            50F
        ),
        Book(
            "978-1-119-42130-6",
            "Professional C++, 4th Edition",
            "Marc Gregoire",
            65F
        ),
        Book(
            "978-1-119-40458-3",
            "Professional Visual Studio 2017",
            "Bruce Johnson",
            65F
        ),
        Book(
            "978-1-119-28497-0",
            "Professional Git",
            "Brent Laster",
            50F
        )
    )
}
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"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="8dp"
        android:text=""
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnInsert" />
    <Button
        android:id="@+id/btnInsert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Insert"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
    <Button
        android:id="@+id/btnSelect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Select Price>$50"
        app:layout_constraintStart_toEndOf="@+id/btnInsert"
        app:layout_constraintTop_toTopOf="parent"
        />
</androidx.constraintlayout.widget.ConstraintLayout>
RoomSingleton.kt

package com.example.roomexamples

import android.content.Context
import androidx.room.*

@Database(entities = arrayOf(Book::class), version = 1, exportSchema = false)

abstract class RoomSingleton : RoomDatabase(){
    abstract fun bookDao(): BookDao
    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.roomexamples

import androidx.room.*


@Entity(tableName = "bookTbl")
data class Book(
    @PrimaryKey
    var ISBN:String,
    var name:String,
    var author:String,
    var price:Float
)


@Dao
interface BookDao{
    @Query("SELECT * FROM bookTbl WHERE price>:price")
    fun allBooks(price:Float):List<Book>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insertBooks(books:List<Book>)
}
app build.gradle [required]

apply plugin: 'kotlin-kapt'

dependencies {
    // Room
    def room_version = "2.2.0-alpha01"
    implementation "androidx.room:room-runtime:$room_version"
    kapt 'androidx.room:room-compiler:2.2.0-alpha01'

    // Anko Commons
    implementation "org.jetbrains.anko:anko-commons:0.10.8"
}