Saturday, July 20, 2019

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

More android examples