AresProductions
AresProductions

Reputation: 518

How to open a closed Room Database

I'm trying to implement a backup feature for my db. To do so, I have to first close the database, then upload the file. After successfully uploading the file, I have trouble re-opening the database.

I'm using Room library.

Here is my Database Code

@Database(
    entities = [Activity::class, Entry::class, EntryActivityJoin::class],
    version = 1,
    exportSchema = false
)
@TypeConverters(LocalDateConverter::class)
abstract class MonkDatabase : RoomDatabase() {
    abstract fun activityDao(): ActivityDao
    abstract fun entryDao(): EntryDao
    abstract fun entryActivityDao(): EntryActivityDao

    companion object {
        @Volatile
        private var instance: MonkDatabase? = null
        private val LOCK = Any()

        operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
            instance ?: buildDatabase(context).also { instance = it }
        }

        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(
                context.applicationContext,
                MonkDatabase::class.java, "monkDatabase.db"
            ).build()
    }
}

So after calling database.close() from my repository, I want to re-open the database again.

Thank you in advance!

Upvotes: 3

Views: 404

Answers (1)

Louis Chabert
Louis Chabert

Reputation: 439

I think you can use this code :

fun importaBkpObservable(origin: File, database: File) {
disposable.clear()
setFlagsNull()

flagSubject.onNext(false)

disposable.add(
        Observable.fromCallable {

            try {

                repo.closeDatabase()

                val myDb = SQLiteDatabase.openOrCreateDatabase(origin, null)
                val ok = myDb.isDatabaseIntegrityOk

                if (myDb.isOpen) myDb.close()

                if(ok) {
                    origin.copyTo(database, true)
                } else {
                    "CORRUPTED DATABASE"
                }

            } catch (t: Throwable) {
                t.message
            }
        }
        .subscribeOn(Schedulers.io())
        .subscribe(
            {
                if(it != null) {
                    if(it is String) {
                        errorFlag = "exportDB: $it"
                        errorSubject.onNext("exportDB: $it")

                    } else {
                        trueFlag = true
                        flagSubject.onNext(true)
                    }

                } else {
                    errorFlag = "exportDB: GENERIC"
                    errorSubject.onNext("exportDB: GENERIC")
                }
            },
            {
                errorFlag = "exportDB: ${it.message}"
                errorSubject.onNext("exportDB: ${it.message}")
            }
        )
)

}

Upvotes: 1

Related Questions