Android Realm Example 示例

Android 数据库主要分三类:

  1. SQLite;
  2. 基于 SQLite 的封装;
  3. 其它数据库引擎。

各有优缺,可参考 Android目前流行三方数据库ORM分析及对比,这里选择 Realm 演示简单的 CRUD。选择 Realm 的一个原因是其在 StackOverflow 上的问题数和 SQLite 在同一个数量级,遇到的问题估计都可以找 StackOverflow

0. Prepare

首先添加相关依赖,在项目配置文件的依赖项中添加如下内容:

classpath "io.realm:realm-gradle-plugin:4.1.1" // 当前最新版 4.1.1

在应用模块配置文件中注明使用 Realm 插件:

apply plugin: 'realm-android'

1. Layout

写一个简单的布局,以便演示,四个按钮,只有一个是写操作,其余三个为查询,单击每条记录将其删除。
activity_realm.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="me.xandeer.examples.realm.RealmActivity">

  <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    app:title="@string/realm"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:navigationIcon="@drawable/ic_toolbar_back" />

  <LinearLayout
    android:id="@+id/input"
    app:layout_constraintTop_toBottomOf="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <EditText
      android:id="@+id/edit_name"
      android:hint="@string/name"
      android:inputType="textCapWords"
      android:layout_width="0dp"
      android:layout_weight="1"
      android:layout_height="44dp" />
    <EditText
      android:id="@+id/edit_age"
      android:hint="@string/age"
      android:inputType="number"
      android:layout_width="0dp"
      android:layout_weight="1"
      android:layout_height="44dp" />
  </LinearLayout>

  <LinearLayout
    android:id="@+id/write"
    app:layout_constraintTop_toBottomOf="@id/input"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
      android:id="@+id/create"
      android:text="@string/create_update"
      android:layout_width="0dp"
      android:layout_weight="1"
      android:layout_height="wrap_content" />
    <Button
      android:id="@+id/all"
      android:text="@string/all"
      android:layout_width="0dp"
      android:layout_weight="1"
      android:layout_height="wrap_content" />
  </LinearLayout>

  <LinearLayout
    android:id="@+id/query"
    app:layout_constraintTop_toBottomOf="@id/write"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <Button
      android:id="@+id/find_by_name"
      android:text="@string/find_by_name"
      android:layout_width="0dp"
      android:layout_weight="1"
      android:layout_height="wrap_content" />
    <Button
      android:id="@+id/find_by_age"
      android:text="@string/find_by_age"
      android:layout_width="0dp"
      android:layout_weight="1"
      android:layout_height="wrap_content" />
  </LinearLayout>

  <ListView
    app:layout_constraintTop_toBottomOf="@+id/query"
    android:id="@+id/persons_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>

2. Model

一个简单的继承自 RealmOjbect 的类。
Person.kt

package me.xandeer.examples.realm

import io.realm.RealmObject
import io.realm.annotations.PrimaryKey

open class Person(
    @PrimaryKey var name: String = "",
    var age: Int = 16
) : RealmObject() {
}

3. CRUD

RealmActivity.kt

3.0 Initialize

Realm 在使用前需要初始化,并获取一个当前线程的实例。

// 在 Activity 的 onCreate 中初始化
Realm.init(this)
// 也可在 Application 的 onCreate 中初始化
// Realm.init(applicationContext)

// 在当前线程获取一个默认的 Realm 实例
realm = Realm.getDefaultInstance()

3.1 Create/Update

create.setOnClickListener {
  if (edit_name.text.isNotEmpty() && edit_age.text.isNotEmpty()) {
    val name = edit_name.text.toString()
    val age = edit_age.text.toString().toInt()
    val person = Person(name, age)

    // 所有写操作都需要在 transaction 中执行
    realm.executeTransaction {
      // create or update
      it.copyToRealmOrUpdate(person)
      log("add person: ${person.name}, ${person.age}")
    }
    edit_age.setText("")
    edit_name.setText("")
  }
}

3.2 Query

all.setOnClickListener {
  val results = realm.where(Person::class.java).findAll()
  show(results)
}

// 条件查询
find_by_name.setOnClickListener {
  if (edit_name.text.isNotEmpty()) {
    val results = realm.where(Person::class.java)
        .equalTo("name", edit_name.text.toString())
        .findAll()
    show(results)
  }
}
...

private fun show(results: RealmResults<Person>) {
  persons.clear()
  results.forEach {
    persons.add("name: ${it.name}, age: ${it.age}")
  }
  (persons_view.adapter as BaseAdapter).notifyDataSetChanged()
}

3.2.1 支持的条件查询语句

  • between(), greaterThan(), lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo()
  • equalTo() & notEqualTo()
  • contains(), beginsWith() & endsWith()
  • isNull() & isNotNull()
  • isEmpty() & isNotEmpty()

3.2.2 对查询结果的操作

  • sort()
  • sum()
  • min()
  • max()
  • average()

3.3 Delete

persons_view.setOnItemClickListener { parent, _, position, _ ->
  val name = parent.getItemAtPosition(position).toString()
      .removePrefix("name: ")
      .substringBefore(", age: ")
  val person = realm.where(Person::class.java)
      .equalTo("name", name)
      .findFirst()!!
  realm.executeTransaction {
    log("delete person: ${person.name}.")
    // remove a single object
    person.deleteFromRealm()
  }
}

3.4 Change Listener

// 数据库内容变化后更新视图
realm.addChangeListener {
  val results = realm.where(Person::class.java).findAll()
  show(results)
}

3.5 Finally

要记得善后:

override fun onDestroy() {
  super.onDestroy()
  realm.removeAllChangeListeners()
  realm.close()
}

更多用法请参考 Realm Java Docs

4. Run

realm-example

5. Code Repository

Github: Android Example

6. Referrence

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容