Wednesday, July 24, 2019

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

More android examples