# IllegalStateException：Room 数据库已关闭且无法使用

- **ID:** `android/illegalstateexception-room-database-close`
- **领域:** android
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

Room 数据库实例已关闭（例如通过 close() 或生命周期销毁），但后续代码尝试执行数据库操作。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Room 2.5.0 | active | — | — |
| Room 2.6.0 | active | — | — |
| Room 2.6.1 | active | — | — |
| Android 13 | active | — | — |
| Android 14 | active | — | — |

## 解决方案

1. ```
   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().
   ```
2. ```
   Add a null check before database operations: `if (database.isOpen()) { database.someDao().query(); }` to avoid accessing closed database.
   ```

## 无效尝试

- **** — 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. (60% 失败率)
- **** — Using `try-catch` to ignore the exception hides the underlying concurrency issue and may lead to data corruption. (80% 失败率)
- **** — Calling `database.close()` in Application.onCreate() thinking it's safe, but it actually closes the singleton instance prematurely. (90% 失败率)
