Error: Cannot access database on the main thread since it may potentially lock the UI for a long period of time. - Android Room using Kotlin

Kleckus

Okay, so, I am trying to use Android Room to create this database for this project.

First of all, this is what I have in my Gradle file regarding the issue:

//Room database
    implementation "androidx.lifecycle:lifecycle-viewmodel:2.1.0"

    implementation "androidx.room:room-runtime:2.2.3"
    kapt "androidx.room:room-compiler:2.2.3"
    implementation "androidx.room:room-ktx:2.2.3"

Here's the Dao Code:

@Dao
interface DebtsDao {

    @Query("SELECT * FROM debts")
    fun getDebtsList() : List<Debts>

    @Query("SELECT * FROM debts WHERE name LIKE :name")
    fun getNamedDebt(name : String) : Debts

    @Insert
    fun insertInDatabase(debt : Debts)

    @Delete
    fun deleteFromDatabase(debt : Debts)

}

The database bit:

@Database(entities = arrayOf(Debts::class), version = 1)
abstract class AppDatabase : RoomDatabase()
{
    abstract fun debtsDao() : DebtsDao
}

And this is the function where I use it:

    fun refreshRecyclerView()
    {
        val database = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "account").build()

        val list : List<Debts> = database.debtsDao().getDebtsList()

        recycler_view_debts.layoutManager = LinearLayoutManager(this)
        recycler_view_debts.adapter = RecAdapter(this, list)
    }

I tried following the tutorial on Android's page, but it didn't work as expected. I got the following error on Android Studio:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.project.watchingmoneyfly, PID: 17067
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.watchingmoneyfly/com.project.watchingmoneyfly.Activities.MainActivity}: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
        at androidx.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:267)
        at androidx.room.RoomDatabase.beginTransaction(RoomDatabase.java:351)
        at com.project.watchingmoneyfly.RoomDatabase.DebtsDao_Impl.insertInDatabase(DebtsDao_Impl.java:79)
        at com.project.watchingmoneyfly.Activities.MainActivity.onCreate(MainActivity.kt:25)
        at android.app.Activity.performCreate(Activity.java:6662)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
        at android.app.ActivityThread.-wrap12(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6077) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

This should be the head of the problem: Cannot access the database on the main thread since it may potentially lock the UI for a long period of time.

What am I missing here? Thanks in advance!!

zsmb13

Room prevents you from using it from the UI thread, because database queries will access the disk, which can take a long time, and blocking the UI thread for that duration will freeze the user interface. You're expected to call Room from a background thread instead, how you get there is up to you. You have a choice of Java threading primitives, Executors, RxJava, coroutines, etc, depending on what you're familiar with.

You can technically circumvent this limitation of Room by using allowMainThreadQueries, but you should never do this in a real application, for the reasons layed out above. This switch is only present for testing.

You can also look into returning a LiveData, Flowable, or similar type that's inherently asynchronous from Room, as in those cases, you're allowed to call Room methods from the UI thread.

See the Room documentation for more info.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Room: Cannot access database on the main thread since it may potentially lock the UI for a long period of time

'Cannot access database on the main thread since it may potentially lock the UI for a long period of time' Also, I Accessed room using coroutine

ّFragment coroutine error:Cannot access database on the main thread since it may potentially lock the UI for a long period of time

How to fix 'Cannot access database on the main thread since it may potentially lock the UI for a long period of time.'

WorkManager : Cannot access database on the main thread since it may potentially lock the UI for a long period of time

"Cannot access database on the main thread since it may potentially lock the UI for a long period of time." error on my Coroutine

Why do I get 'Cannot access database on the main thread since it may potentially lock the UI for a long period of time.' error in Android Studio?

Android Room database RxAndroid, Exception : java.lang.IllegalStateException: Cannot access database on the main thread since

Android Room - Cannot access database on the main thread

Android Room - simple select query - Cannot access database on the main thread

Room: Cannot access database on the main thread *but*

Android - Kotlin Coroutines for handling IllegalStateException: Cannot access database on the main thread

Room Database Error when espresso test "Cannot access database on the main thread"

Insert data with room from view : Cannot access database on the main thread

Error With ROOM Database in Android Kotlin

Android Studio Kotlin Room database error

RxJava2 with Room error handling - Database main thread exception

Room database using kotlin

Is keeping a lock on a record for a long period of time common practice with modern database systems?

Cannot find setter for field - using Kotlin with Room database

Android Room library error: Cannot find setter for field. (Kotlin)

Android - Kotlin - Prepoluate room database

Cannot update UI on main thread

Android Room - error: Cannot figure out how to save this field into database

Android BroadcastReceiver Database Access with Room

Return data outside the main thread in Android Room

Executing delete in main thread room using RxJava

Room cannot pick a constructor since multiple constructors are suitable error

Error reading Android SQLite database using Kotlin

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive