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'
}