Avatar ·

Android Room: how to fix "Cannot access database on the main thread" error with a simple SELECT query?

Hello everyone! I'm a beginner in Android development with Kotlin and I'm using Room for a local database. I have a simple User entity and a DAO with a getAllUsers() method that returns a list of all users. I call this method from an Activity to display data in a RecyclerView. But the app crashes with the error:

\n\n
java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
\n\n

Here is my code:

\n\n
// Entity\n@Entity(tableName = "users")\ndata class User(\n    @PrimaryKey val id: Int,\n    val name: String,\n    val email: String\n)\n\n// DAO\n@Dao\ninterface UserDao {\n    @Query("SELECT * FROM users")\n    suspend fun getAllUsers(): List<User>\n}\n\n// Database