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?