“Object” is not part of the schema for this Realm

2019-01-28 07:21发布

问题:

When I call the realm.where(MessageEventModel::class.java).findAll()

it throws excepiton: this is error

java.lang.IllegalArgumentException: MessageEventModel is not part of the schema for this Realm
                                                                          at io.realm.internal.modules.CompositeMediator.getMediator(CompositeMediator.java:172)
                                                                     at io.realm.internal.modules.CompositeMediator.getTableName(CompositeMediator.java:90)

this is my Application class

class MyApp : Application() {

override fun onCreate() {
    super.onCreate()
    Realm.init(this)
    val realmConfiguration = RealmConfiguration.Builder()
            .deleteRealmIfMigrationNeeded()
            .name("my_db")
            .build()
    Realm.setDefaultConfiguration(realmConfiguration)
}
}

this is my Realm Model

class MessageEventModel : RealmObject{
  constructor()
  var message = ""
  constructor(message: String) : this(){
    this.message = message
  }
}

And here is where I'm trying to retrieve models

class AwesomeChatFragment : Fragment() {

private val realm: Realm by lazy { Realm.getDefaultInstance() }
private var notifications: RealmResults<MessageEventModel>? = null

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater?.inflate(R.layout.activity_awesome_chat, container, false)
    notifications = realm.where(MessageEventModel::class.java).findAll()
    return view
}
}

gradle configuration:

apply plugin: 'com.android.application'
apply plugin: 'realm-android'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'


buildscript {
    ext.kotlin_version = '1.1.1'
    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath "io.realm:realm-gradle-plugin:3.0.0"
    }
}

I tried everything what I could found on stack: clean build, rebuild project, enable annotation processor, reinstaling apk, invalidate caches / restart

回答1:

The issue where in gradle file.The problem where just an ordering rules of applying plugins, thanks to the @EpicPandaForce's comment, the problem has been solved, I'm writing answer, for helping others, if they miss the commented answer from @EpicPandaForce

I changed the ordering of

apply plugin: 'com.android.application'
apply plugin: 'realm-android'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

to

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'realm-android'

That's all, now everything works fine