Captain Jacky
Captain Jacky

Reputation: 1059

How to detect open/close connection change in SQLite Android?

is there a way to detect when SQLite connection closes? I am trying to integrate SQLCipher and this is the initialization method:

fun initialize(passphrase: String): Boolean {
    this.passphrase = SQLiteDatabase.getBytes(passphrase.toCharArray())
    this.factory = SupportFactory(this.passphrase, PasswordValidationHook(), false)

    return try {
        myDatabase = Room.databaseBuilder(
            context.applicationContext,
            MyDatabase::class.java,
            DATABASE_NAME
        )
            .openHelperFactory(factory)
            .build()

        myDatabase.query("SELECT 1", emptyArray())

        true
    } catch (e: Exception) {
        false
    }
}

Now if the connection gets opened I know after the line myDatabase.query("SELECT 1", emptyArray()). However, I cannot find a proper way to detect when the database closes connection, since I have a notification service which displays whether the database is open or not.

I could close the connection manually on onDestroy method and have a listener attached, however, it's not recommended, since this method is not always called.

Upvotes: -1

Views: 76

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93614

There is no connection in SQLite. This isn't a traditional DB where it's another process. It's a library, and it does direct file IO in the process that's currently running. Thus no connection, no IPC to another process, and no closing or opening of a connection. The helper there with DATABASE_NAME "opening" it is just telling it what DB file to use for that object

Upvotes: 0

Related Questions