Android 數(shù)據(jù)庫主要分三類:
- SQLite;
- 基于 SQLite 的封裝;
- 其它數(shù)據(jù)庫引擎。
各有優(yōu)缺,可參考 Android目前流行三方數(shù)據(jù)庫ORM分析及對比,這里選擇 Realm 演示簡單的 CRUD。選擇 Realm 的一個原因是其在 StackOverflow 上的問題數(shù)和 SQLite 在同一個數(shù)量級,遇到的問題估計都可以找 StackOverflow。
0. Prepare
首先添加相關(guān)依賴,在項目配置文件的依賴項中添加如下內(nèi)容:
classpath "io.realm:realm-gradle-plugin:4.1.1" // 當(dāng)前最新版 4.1.1
在應(yīng)用模塊配置文件中注明使用 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
3.0 Initialize
Realm 在使用前需要初始化,并獲取一個當(dāng)前線程的實例。
// 在 Activity 的 onCreate 中初始化
Realm.init(this)
// 也可在 Application 的 onCreate 中初始化
// Realm.init(applicationContext)
// 在當(dāng)前線程獲取一個默認的 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 中執(zhí)行
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 對查詢結(jié)果的操作
- 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
// 數(shù)據(jù)庫內(nèi)容變化后更新視圖
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