Error "Cannot access database on the main thread" in Android Room on Kotlin
Hi! I'm a beginner in Android development on Kotlin and using Room for local data storage. I wrote a simple SELECT query, but the app crashes with the error: "Cannot access database on the main thread". Here's my code:\n\n```kotlin\n// DAO\n@Dao\ninterface UserDao {\n @Query("SELECT * FROM users WHERE id = :userId")\n fun getUser(userId: Int): User\n}\n\n// Activity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n \n val db = Room.databaseBuilder(\n applicationContext,\n AppDatabase::class.java, \n "my-db"\n ).build()\n \n val user = db.userDao().getUser(1) // Error here
No answers yet.
Log in to leave an answer
Blogs