android runtime_error ai_generated true

IllegalStateException: Room database is already closed and cannot be used

ID: android/illegalstateexception-room-database-close

Also available as: JSON · Markdown · 中文
88%Fix Rate
85%Confidence
1Evidence
2023-03-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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/room

Workarounds

  1. 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().
  2. 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.

中文步骤

  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.

Dead Ends

Common approaches that don't work:

  1. 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.

  2. 80% fail

    Using `try-catch` to ignore the exception hides the underlying concurrency issue and may lead to data corruption.

  3. 90% fail

    Calling `database.close()` in Application.onCreate() thinking it's safe, but it actually closes the singleton instance prematurely.