-1

I'm using the Realm database in my kotlin project. I use MVVM architecture so I created a repository class which contains codes bellow:

class DatabaseRepository {
    private val database = Realm.getDefaultInstance()

    fun addOrUpdateUser(user: JSONObject) {
        database.executeTransactionAsync{
            database.createOrUpdateObjectFromJson(UserModel::class.java, user)
        }
    }
}

also, I have created my ViewModel class like this:

class DatabaseViewModel(private val database:DatabaseRepository) : ViewModel() {


    fun addUser(information: JSONObject) {
        database.addOrUpdateUser(information)
    }

}

and my View ModelFactory class is like this:

class ViewModelFactory(private val databaseRepository:DatabaseRepository):ViewModelProvider.Factory {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return modelClass.getConstructor(DatabaseRepository::class.java).newInstance(databaseRepository)
    }
}

so I create the instance of them in my MainActivity like this:

val databaseRepo=DatabaseRepository()
val factory=ViewModelFactory(databaseRepo)
database = ViewModelProviders.of(this,factory).get(DatabaseViewModel::class.java)

the problem is that while I'm trying to add some data to Database using 'addUser' function in ViewModel class I get this error:

Realm objects can only be accessed on the thread they were created.

what have I done wrong?

Mohammad Derakhshan
  • 1,262
  • 11
  • 33
  • A quick [search](https://stackoverflow.com/questions/40344801/realm-access-from-incorrect-thread) returned a solution to the problem. – Taseer Mar 14 '20 at 18:38

1 Answers1

0

the only problem was because of executeTransactionAsync, so I changed from:

executeTransactionAsync

to

executeTransaction

and it worked!

Mohammad Derakhshan
  • 1,262
  • 11
  • 33