Application Not Responding (ANR) errors are the leading cause of low Play Store ratings. In many cases, these are caused by SQLite database operations running on the main thread, especially during large transactions or database migrations.

The allowMainThreadQueries Danger

While Room (the SQLite wrapper) allows you to bypass thread checks for debugging, leaving this enabled in production is a recipe for disaster. Small queries might seem fast, but as the database grows, they will eventually block the UI.

Wrong Approach Room.databaseBuilder(...).allowMainThreadQueries().build() // AVOID THIS

Using Coroutines for DB Ops

The modern solution is to use Kotlin Coroutines. Room has first-class support for suspend functions, making it easy to offload work to Dispatchers.IO.

Coroutines Example @Dao
interface UserDao {
@Query("SELECT * FROM users")
suspend fun getAll(): List<User>
}

Transaction Optimization

When inserting hundreds of items, wrap them in a single transaction. Doing 500 individual inserts is massively slower than one transaction containing 500 inserts due to disk I/O overhead.

Room Transaction db.withTransaction {
dao.insertAll(list)
}

Summary

Keep your database off the main thread, use transactions for batch work, and leverage Coroutines for asynchronous access. A smooth UI is a happy UI!