13.9 添加日程实体类

我们先从领域模型的建立开始。首先我们需要设计一个极简的待办事项的实体类 Todo, 它有主键 id、标题、内容三个字段。

  1. @RealmClass
  2. open class Todo : RealmObject() {
  3. @PrimaryKey
  4. open var id: String = "-1"
  5. open var title: String = "日程"
  6. open var content: String = "事项"
  7. }

然后,我们写一个应用程序入口类MyTodoApplication继承android.app.Application, 在 onCreate() 里面初始化 Realm 数据库的配置。代码如下:

  1. class MyTodoApplication : Application() {
  2. override fun onCreate() {
  3. super.onCreate()
  4. val config = RealmConfiguration.Builder(this)
  5. .name("realm.my_todos")// 库文件名
  6. .encryptionKey(getKey()) // 加密
  7. .schemaVersion(1) // 版本号
  8. .deleteRealmIfMigrationNeeded()
  9. .build()
  10. Realm.setDefaultConfiguration(config)// 设置默认 RealmConfiguration
  11. }
  12. /**
  13. * 64 bits
  14. * @return
  15. */
  16. private fun getKey(): ByteArray {
  17. return byteArrayOf(0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1)
  18. }
  19. }

RealmConfiguration.Builder里面如果没有deleteRealmIfMigrationNeeded()的话,会如下报错误:

  1. Caused by: io.realm.exceptions.RealmMigrationNeededException:
  2. RealmMigration must be provided ...
  3. at com.easy.kotlin.mytodoapplication.TodoListFragment.onActivityCreated(TodoListFragment.kt:36)

提示: 更多关于 realm 数据库的相关内容可参考 https://realm.io/docs/