# IllegalStateException: Room database is already closed and cannot be used

- **ID:** `android/illegalstateexception-room-database-close`
- **Domain:** android
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 88%

## Root Cause

A Room database instance was closed (e.g., via close() or lifecycle destruction) but code tries to perform database operations afterwards.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Room 2.5.0 | active | — | — |
| Room 2.6.0 | active | — | — |
| Room 2.6.1 | active | — | — |
| Android 13 | active | — | — |
| Android 14 | active | — | — |

## Workarounds

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

## Dead Ends

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