realm / realm-java

Realm is a mobile database: a replacement for SQLite & ORMs
http://realm.io
Apache License 2.0
11.46k stars 1.75k forks source link

java.lang.IllegalArgumentException: Model is not part of the schema for this Realm #6382

Closed niteshrrathore closed 5 years ago

niteshrrathore commented 5 years ago

I'm beginner with kotlin and trying to use realm, and I'm getting a crash in app.

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.iziss6.kotlinsample, PID: 16073 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iziss6.kotlinsample/com.example.iziss6.kotlinsample.HomeActivity}: java.lang.IllegalArgumentException: OrderDetailsModel is not part of the schema for this Realm at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3062) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1756) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:192) at android.app.ActivityThread.main(ActivityThread.java:6806) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:445) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:867) Caused by: java.lang.IllegalArgumentException: OrderDetailsModel is not part of the schema for this Realm at io.realm.internal.modules.CompositeMediator.getMediator(CompositeMediator.java:169) at io.realm.internal.modules.CompositeMediator.getTableName(CompositeMediator.java:87) at io.realm.RealmSchema.getTable(RealmSchema.java:218) at io.realm.RealmSchema.getSchemaForClass(RealmSchema.java:239) at io.realm.RealmQuery.(RealmQuery.java:122) at io.realm.RealmQuery.createQuery(RealmQuery.java:76) at io.realm.Realm.where(Realm.java:1342) at com.example.iziss6.kotlinsample.realm.RealmController.getOrderDetailsModel(RealmController.kt:26) at com.example.iziss6.kotlinsample.HomeActivity.getOrderDetailsModelData(HomeActivity.kt:322) at com.example.iziss6.kotlinsample.HomeActivity.onCreate(HomeActivity.kt:115) at android.app.Activity.performCreate(Activity.java:7144) at android.app.Activity.performCreate(Activity.java:7135) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1219) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2937) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3062)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1756)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:192)  at android.app.ActivityThread.main(ActivityThread.java:6806)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:445)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:867) 

build.gradle(Project: KotlinSample)

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

android { compileSdkVersion 28 defaultConfig { multiDexEnabled true applicationId "com.example.iziss6.kotlinsample" minSdkVersion 17 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } }

dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

implementation('de.keyboardsurfer.android.widget:crouton:1.8.5@aar') {
    // exclusion is not necessary, but generally a good idea.
    exclude group: 'com.google.android', module: 'support-v4'
}
//retrofit & OkHttp
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
implementation 'com.squareup.okhttp3:okhttp:3.8.0'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.8.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'
implementation 'com.github.PhilJay:MPAndroidChart:v2.2.5'
//compile 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
implementation 'me.sudar:zxing-orient:2.1.1@aar'
// compile 'com.google.zxing:core:3.2.0'
implementation('me.zhanghai.android.materialprogressbar:library:1.3.0') {
    transitive = false;
}

implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.google.android.gms:play-services:11.4.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation('com.cheekiat:slideview:1.3') {
    transitive = false;
}
implementation 'com.android.support:multidex:1.0.3'

} repositories { mavenCentral() }

build.gradle(Module:app)

buildscript { ext.kotlin_version = '1.2.71'

repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    //classpath "io.realm:realm-gradle-plugin:5.8.0"
    classpath "io.realm:realm-gradle-plugin:3.5.0"

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

}

allprojects { repositories { google() jcenter() maven { url "https://jitpack.io" } } }

task clean(type: Delete) { delete rootProject.buildDir }

Model Class

class OrderDetailsModel : RealmObject() {

@SerializedName("message")
@Expose
var message: String? = null

@SerializedName("clsProjectDetails")
@Expose
var projectDetailsList: RealmList<ProjectDetailsModel>? = null

@SerializedName("status")
@Expose
var status: String? = null

@SerializedName("Company")
@Expose
var company: String? = null

@SerializedName("statuscode")
@Expose
var statuscode: String? = null

override fun toString(): String {
    return "ClassPojo [message = $message, clsProjectDetails = $projectDetailsList, status = $status, Company = $company, statuscode = $statuscode]"
}

}

RealmController.kt

class RealmController(application: Application) { val realm: Realm

val orderDetailsModel: OrderDetailsModel?
    get() = realm.where(OrderDetailsModel::class.java).findFirst()

val allPendingTaskList: List<PendingTask>
    get() = ArrayList(realm.where(PendingTask::class.java).equalTo("status", "0").findAll())

/***
 * @return
 */
val isAnyPendingRequest: Boolean
    get() {

        val list = ArrayList(realm.where(PendingTask::class.java).equalTo("status", "0").findAll())

        return if (list == null) {
            false
        } else if (list.size == 0) {
            false
        } else {
            true
        }

    }

/***
 * @return
 */
//ArrayList<Messages> list = new ArrayList(realm.where(Messages.class).findAllSorted("messageID"));
val allPendingRequestWithStatus: List<PendingTask>
    get() = ArrayList(realm.where(PendingTask::class.java).equalTo("status", "0").or().equalTo("status", "2").findAll())

/***
 * @return
 */
val allFailedPendingRequests: List<PendingTask>
    get() = ArrayList(realm.where(PendingTask::class.java).equalTo("status", "2").findAll())

init {
    realm = Realm.getDefaultInstance()
}

//Refresh the realm istance
fun refresh() {

    realm.refresh()
}

fun insertOrUpdateClient(orderDetailsModel: OrderDetailsModel) {

    try {

        // I could use try-with-resources here
        realm.executeTransaction { realm -> realm.insertOrUpdate(orderDetailsModel) }
    } catch (ex: Exception) {

    } finally {

        /*if (realm != null) {
            realm.close();
        }*/
    }

}

fun deleteRealm() {
    try {

        // I could use try-with-resources here
        realm.executeTransaction { realm ->
            realm.deleteAll()

            // realm.createObjectFromJson(AllClient.class, "{ city: \"Copenhagen\", id: 1 }");
        }
    } catch (ex: Exception) {

    } finally {
    }
}

fun insertOrUpdateTask(mPendingTask: PendingTask, isExist: Boolean?) {

    try {
        realm.executeTransaction { realm ->
            if (isExist!!) {
                realm.copyToRealmOrUpdate(mPendingTask)
            } else {
                realm.insert(mPendingTask)
            }
        }
    } catch (ex: Exception) {
        ex.printStackTrace()

    } finally {

    }
}

fun getLastInsertedTaskForUpdate(pendingTask: PendingTask): Boolean? {

    val Task = realm.where(PendingTask::class.java).equalTo("id", pendingTask.id).findFirst()

    return if (Task != null) {
        true
    } else false
}

/***
 * @return
 */
fun deletePendingRequestOnSuccess(id: String, status: String) {

    val toEdit = realm.where(PendingTask::class.java).equalTo("id", id).findFirst()

    realm.executeTransaction {
        toEdit?.deleteFromRealm()
    }

}

fun updatePendingRequestStatus(id: String, status: String) {

    val toEdit = realm.where(PendingTask::class.java).equalTo("id", id).findFirst()
    realm.beginTransaction()
    toEdit!!.status = status
    realm.commitTransaction()
}

/***
 * @return
 */
fun deleteFailedRequests() {

    val list = realm.where(PendingTask::class.java).equalTo("status", "2").findAll()
    realm.executeTransaction { list.deleteAllFromRealm() }

}

companion object {

    private val TAG = "RealmController"
    var instance: RealmController? = null

    fun with(fragment: Fragment): RealmController {

        if (instance == null) {
            instance = RealmController(fragment.activity!!.application)
        }
        return instance as RealmController
    }

    fun with(activity: Activity): RealmController {

        if (instance == null) {
            instance = RealmController(activity.application)
        }
        return instance as RealmController
    }

    fun with(mService: Service): RealmController {

        if (instance == null) {
            instance = RealmController(mService.application)
        }
        return instance as RealmController
    }

    fun with(application: Application): RealmController {

        if (instance == null) {
            instance = RealmController(application)
        }
        return instance as RealmController
    }

}

}

HomeActivity.kt private var mRealmController: RealmController? = null var orderDetailModel: OrderDetailsModel? = OrderDetailsModel()

override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_dash_board)

    Realm.init(this@HomeActivity)

    mRealmController = RealmController.with(this@HomeActivity)

    orderDetailModel = mRealmController!!.orderDetailsModel

}

Android Studio version: 3.2.1

Gradle version: distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip

cmelchior commented 5 years ago

Since you are using Kotlin. Do you have the following plugins in that order?

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'

As described here: https://realm.io/docs/java/latest#kotlin

Zhuinden commented 5 years ago

He is missing kotlin-kapt and that is why this exception is happening

cmelchior commented 5 years ago

Ah yeah, missed that the app level plugins was actually mentioned 👍

niteshrrathore commented 5 years ago

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

android { compileSdkVersion 28 defaultConfig { multiDexEnabled true applicationId "com.example.iziss6.kotlinsample" minSdkVersion 17 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } }

/realm { kotlinExtensionsEnabled = false // Disable extensions if needed }/

dependencies {

implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation

'com.android.support.test.espresso:espresso-core:3.0.2' implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" //implementation "org.jetbrains.anko:anko-commons:0.10.4"

implementation('de.keyboardsurfer.android.widget:crouton:1.8.5@aar') {
    // exclusion is not necessary, but generally a good idea.
    exclude group: 'com.google.android', module: 'support-v4'
}
//retrofit & OkHttp
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
implementation 'com.squareup.okhttp3:okhttp:3.8.0'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.8.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'
implementation 'com.github.PhilJay:MPAndroidChart:v2.2.5'
//compile 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
implementation 'me.sudar:zxing-orient:2.1.1@aar'
// compile 'com.google.zxing:core:3.2.0'
implementation('me.zhanghai.android.materialprogressbar:library:1.3.0') {
    transitive = false;
}

implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.google.android.gms:play-services:11.4.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation('com.cheekiat:slideview:1.3') {
    transitive = false;
}
implementation 'com.android.support:multidex:1.0.3'

kapt 'groupId:artifactId:version'

}

kapt { generateStubs = true }

repositories { mavenCentral() }

even i getting the same issue. And if i'm doing wrong than can you provide me the kapt plugin code.

On Fri, Jan 4, 2019 at 3:25 PM Christian Melchior notifications@github.com wrote:

Ah yeah, missed that the app level plugins was actually mentioned 👍

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/realm/realm-java/issues/6382#issuecomment-451400209, or mute the thread https://github.com/notifications/unsubscribe-auth/AYXZVZflsGZjvt287yUVcKcj_oAukCxeks5u_yT6gaJpZM4ZpQpP .

Zhuinden commented 5 years ago

Well now it's there but now it should work. Have you tried clean rebuild?

niteshrrathore commented 5 years ago

Thanks for your support, i got the mistake that is "i didn't use Realm.setDefaultConfiguration(config) command for schema