Realm x Kotlin

开此贴用于记录在 Android 中使用 Realm 的坑,给以后一不小心踏进坑里的小伙伴提供一点帮助

开发语言:Kotlin
Realm version: 5.7.0
kotlin version: 1.2.71
gradle: 3.2.1

#1 is not part of the schema for this Realm. Did you added realm-android plugin in your build.gradle file?

  1. 首先检查你的配置和官网当中的是否一致

    《Realm x Kotlin》 realm官网配置

  2. 如果与官网配置一致仍然报这个问题,检查你的类是否使用了注解,如 @PrimaryKey
open class LightType(
  @PrimaryKey var id: String,
  var type: String
) : RealmObject()

如有,检查根目录下的build.gradle,在realm-android前添加 kotlin-kapt

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

apply plugin: 'realm-android'

#2 e: 错误: Class “XXXX” must declare a public constructor with no arguments if it contains custom constructors.

查看自己的实现类

open class Light(
  @PrimaryKey var id: String,
  var content: String,
  var type: LightType?
) : RealmObject()

kotlin 的实现需要给属性默认值,给属性添加默认值即可,如下👇

open class Light(
  @PrimaryKey var id: String = UUID.randomUUID().toString(),
  var content: String ="",
  var type: LightType? = null
) : RealmObject()

缓更

    原文作者:氢电公敌
    原文地址: https://www.jianshu.com/p/9efe46baefea
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞