android
runtime_error
ai_generated
true
IllegalStateException: Room database is already closed and cannot be used
ID: android/illegalstateexception-room-database-close
88%Fix Rate
85%Confidence
1Evidence
2023-03-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Room 2.5.0 | active | — | — | — |
| Room 2.6.0 | active | — | — | — |
| Room 2.6.1 | active | — | — | — |
| Android 13 | active | — | — | — |
| Android 14 | active | — | — | — |
Root Cause
A Room database instance was closed (e.g., via close() or lifecycle destruction) but code tries to perform database operations afterwards.
generic中文
Room 数据库实例已关闭(例如通过 close() 或生命周期销毁),但后续代码尝试执行数据库操作。
Official Documentation
https://developer.android.com/training/data-storage/roomWorkarounds
-
90% success Use a singleton pattern for the database instance and ensure it is never closed manually; let the Application lifecycle manage it. Example: `AppDatabase.getInstance(context)` always returns the same instance without close().
Use a singleton pattern for the database instance and ensure it is never closed manually; let the Application lifecycle manage it. Example: `AppDatabase.getInstance(context)` always returns the same instance without close().
-
85% success Add a null check before database operations: `if (database.isOpen()) { database.someDao().query(); }` to avoid accessing closed database.
Add a null check before database operations: `if (database.isOpen()) { database.someDao().query(); }` to avoid accessing closed database.
中文步骤
Use a singleton pattern for the database instance and ensure it is never closed manually; let the Application lifecycle manage it. Example: `AppDatabase.getInstance(context)` always returns the same instance without close().
Add a null check before database operations: `if (database.isOpen()) { database.someDao().query(); }` to avoid accessing closed database.
Dead Ends
Common approaches that don't work:
-
60% fail
Reopening the database manually with `Room.databaseBuilder(context, AppDatabase.class, "db").build()` creates a new instance but may cause memory leaks if old references persist.
-
80% fail
Using `try-catch` to ignore the exception hides the underlying concurrency issue and may lead to data corruption.
-
90% fail
Calling `database.close()` in Application.onCreate() thinking it's safe, but it actually closes the singleton instance prematurely.