android
runtime_error
ai_generated
true
IllegalStateException:Room 数据库已关闭且无法使用
IllegalStateException: Room database is already closed and cannot be used
ID: android/illegalstateexception-room-database-close
88%修复率
85%置信度
1证据数
2023-03-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Room 2.5.0 | active | — | — | — |
| Room 2.6.0 | active | — | — | — |
| Room 2.6.1 | active | — | — | — |
| Android 13 | active | — | — | — |
| Android 14 | active | — | — | — |
根因分析
Room 数据库实例已关闭(例如通过 close() 或生命周期销毁),但后续代码尝试执行数据库操作。
English
A Room database instance was closed (e.g., via close() or lifecycle destruction) but code tries to perform database operations afterwards.
官方文档
https://developer.android.com/training/data-storage/room解决方案
-
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.
无效尝试
常见但无效的做法:
-
60% 失败
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% 失败
Using `try-catch` to ignore the exception hides the underlying concurrency issue and may lead to data corruption.
-
90% 失败
Calling `database.close()` in Application.onCreate() thinking it's safe, but it actually closes the singleton instance prematurely.