0

I'm packing all realm operation inside one object:

object RealmDatabase {

    private val config = RealmConfiguration.Builder().name("XXX").build()

    init {
        Realm.setDefaultConfiguration(config)
    }

    fun getClassTimetables() : RealmResults<TimetableData> {
        val realm = Realm.getDefaultInstance()
        realm.use {
            return realm.where<TimetableData>().findAll()
        }
    }

    fun addClassTimetables(data: List<TimetableData>) {
        val realm = Realm.getDefaultInstance()
        realm.use {
            realm.executeTransaction { transactionRealm ->
                transactionRealm.copyToRealm(data)
            }
        }
    }

    fun emptyClassTimetable() {
        Realm.getDefaultInstance().executeTransaction { transactionRealm ->
            transactionRealm.where<TimetableData>().findAll().deleteAllFromRealm()
        }
    }
}

When I call RealmDatabase.getClassTimetables(), the exception was thrown:
This Realm instance has already been closed, making it unusable.
But I have already obtain one default instance and always make sure it was closed when operation was finished.
What's wrong with my code?

Hhry
  • 823
  • 1
  • 8
  • 19
  • 1
    It sounds like there's only one default instance and that maybe you shouldn't be closing it? – Louis Wasserman Nov 15 '22 at 05:36
  • Are you instantiating the RealmDatabase object each time you want to use it or... how is it being used? How are you *making sure it was closed* e.g. the code in the question is a little vague/incomplete. It sounds like it's a reference counting issue where it's closes ≠ opens. – Jay Nov 15 '22 at 19:23

0 Answers0