Cannot access database on the main thread 🤖 Android

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

A Room DAO query ran on the main thread; Room forbids it by default.

Seen on: Android

Meaning

Make DAO methods suspend or return Flow/LiveData so Room runs them off the main thread. allowMainThreadQueries() is only for tests.

Common causes

  • Non-suspend DAO call from Activity/ViewModel main thread
  • Blocking call inside a main-thread coroutine

⚡ Quick fix

  1. Use suspend DAO functions or Flow
  2. Call from viewModelScope (Room switches dispatcher)
  3. Avoid allowMainThreadQueries

Detailed fix by platform

Kotlin

  1. kotlin
    @Dao interface UserDao {
        @Query("SELECT * FROM user WHERE id = :id") suspend fun get(id: Long): User?
        @Query("SELECT * FROM user") fun all(): Flow<List<User>>
    }

How to diagnose

  1. DAO — suspend/Flow?
  2. Caller — Thread/dispatcher

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.