You are reading the documentation for an older version of Realm. You can view the latest documentation instead.

Realm Java 让你能够高效地编写app的模型层代码,保证你的数据被安全、快速地存储。参考下列示例来开始你的Realm之旅:

// Define you model class by extending the RealmObject
public class Dog extends RealmObject {
    @Required // Name cannot be null
    private String name;
    private int age;

    // ... Generated getters and setters ...
}
public class Person extends RealmObject {
    @Required // Name is not nullable
    private String name;
    private String imageUrl; // imageUrl is an optional field
    private RealmList<Dog> dogs;

    // ... Generated getters and setters ...
}

// Use them like regular java objects
Dog dog = new Dog();
dog.setName("Rex");
Log.v(TAG, "Name of the dog: " + dog.getName());

// Get a Realm instance for this thread
Realm realm = Realm.getInstance(context);

// Persist your data easily
realm.beginTransaction();
realm.copyToRealm(dog);
realm.commitTransaction();

// Query and use the result in another thread
Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        // Get a Realm instance for this thread
        Realm realm = Realm.getInstance(context);
        Dog dog = realm.where(Dog.class).equalTo("name", "Rex").findFirst();
        Log.v(TAG, "Age of the dog: " + dog.getAge());
        realm.close();
    }
});
thread.start();
'''

## 快速入门

<a class="btn btn-lg btn-primary" href="https://static.realm.io/downloads/java/realm-java-4.3.1.zip" onclick="that=this;var timeoutFunc;ga('send', {'hitType': 'event', 'eventCategory': 'Downloads', 'eventAction': 'Download - Java', 'eventLabel': 'Download', 'hitCallback': function(){ location.href = that.href; clearTimeout(timeoutFunc);}});timeoutFunc = setTimeout(function(){location.href = that.href;}, 1500);return false;">下载Realm Android</a>
或者在[GitHubrealm-java页面](https://github.com/realm/realm-java)查看源代码.

<!--div class="flex-video widescreen install-video-container">
<iframe width="420" height="315" src="//www.youtube.com/embed/tr6peMnquDQ?rel=0" frameborder="0" allowfullscreen></iframe>
</div-->

### 前提

* 目前我们还不支持Android以外的Java环境;
* Android Studio >= 0.8.6;如果您要在Eclipse中使用Realm,见下文;
* 较新的 Android SDK 版本;
* JDK版本>=7
* 我们支持Android API 9以上的所有版本(Android 2.3 Gingerbread及以上)。

### 安装

<ul class="nav nav-tabs getting-started" role="tablist"><li class="active"><a href="#android-studio" role="tab" data-toggle="tab">Android Studio</a></li><li><a href="#eclipse" role="tab" data-toggle="tab">Eclipse</a></li></ul>
<div class="tab-content getting-started">
<div class="tab-pane active" id="android-studio">

您可以使用Maven或手动添加一个Jar包到项目中。

#### Maven

0. **确保您的项目使用 _jcenter_ 作为依赖仓库** (最新版本Android Gradle插件的默认设置);
1. 将 `compile 'io.realm:realm-android:0.87.0'` 添加到您的项目依赖;
2. 在Android Studio菜单中选择:Tools->Android->Sync Project with Gradle Files。

#### Jar

0. <a href="https://static.realm.io/downloads/java/realm-java-4.3.1.zip" onclick="that=this;var timeoutFunc;ga('send', {'hitType': 'event', 'eventCategory': 'Downloads', 'eventAction': 'Download - Java', 'eventLabel': 'Download', 'hitCallback': function(){ location.href = that.href; clearTimeout(timeoutFunc);}});timeoutFunc = setTimeout(function(){location.href = that.href;}, 1500);return false;">下载</a>发布包,并解压;
1. 使用Android Studio创建一个新项目;
2. 把`realm-VERSION.jar`文件夹复制到 `app/libs`;
3. Android Studio菜单中选择:Tools->Android->Sync Project with Gradle Files

</div>

<div class="tab-pane" id="eclipse">

0. <a href="https://static.realm.io/downloads/java/realm-java-4.3.1.zip" onclick="that=this;var timeoutFunc;ga('send', {'hitType': 'event', 'eventCategory': 'Downloads', 'eventAction': 'Download - Java', 'eventLabel': 'Download', 'hitCallback': function(){ location.href = that.href; clearTimeout(timeoutFunc);}});timeoutFunc = setTimeout(function(){location.href = that.href;}, 1500);return false;">下载</a>发布包,并解压;
1. 从`distribution/eclipse/`目录中复制jar文件和文件夹(包含 `librealm-jni.so` 文件)到app的`libs`目录;
2. 在`libs`文件夹中右键单击realm jar文件,选择“Build Path -> Add to Build path”;
3. 右键单击您的项目,选择“Properties”,进入“Java Compiler -> Annotation Processing”,勾选“Enable project specific settings”,然后选择“Apply”;
  <img class="img-responsive img-rounded" src="/assets/img/docs/eclipse_annotation_processing.png" />
4. 继续选择“Annotation Processing” -> “Factory Path”并勾选“Enable project specific settings”; “Click Add JARs”,然后在“libs”中选择realm jar文件,单击"OK",应用,并开始编译;
  <img class="img-responsive img-rounded" src="/assets/img/docs/eclipse_factory_path.png" />
5. 为了触发注解处理器(annotation processor),您必须在每一个RealmObject子类声明前添加`@RealmClass`。

</div>
</div>


### ProGuard

在编译时,Realm为各RealmObject生成一个代理类。为了确保这些类在经过代码混淆工具如[ProGuard](http://developer.android.com/tools/help/proguard.html)处理后仍然可见,添加下面的配置到您的ProGuard配置文件中。**(Realm版本应至少是0.84.1)**

-keep class io.realm.annotations.RealmModule -keep @io.realm.annotations.RealmModule class * -keep class io.realm.internal.Keep -keep @io.realm.internal.Keep class * { *; } -dontwarn javax.** -dontwarn io.realm.** ‘’’

Realm浏览器

目前仅支持Mac OS X。
Windows和Linux版本正在开发中。

我们还提供了一个独立的应用程序Realm Browser来读写.realm数据库。

您可以通过Tools > Generate demo database生成一个测试数据库。

查阅StackOverflow上的这个答案 获得有关您的应用程序Realm文件路径的详细说明。

Realm Browser已经上架Map App Store

API手册

您可以查阅API手册获得所有关于类、方法及其它细节的信息。

示例

根目录包含有关Realm入门的几个例子。您只需在Android Studio中导入运行即可。

根目录中的RealmIntroExample包含了如何使用当前的API的简单例子。请查阅源代码来获取相关信息。

RealmGridViewExample用来展示如何使用Realm作为GridView的后端存储。它同时也展示了如何用JSON来填充数据库。

RealmThreadExample展示了如何在多线程环境中使用Realm。

RealmAdapterExample展示了如何以一个非常便捷的方式使用RealmBaseAdapter绑定RealmResults到安卓的ListView。

RealmJsonExample展示了Realm与JSON相关的功能。

RealmEncryptionExample向您展示如何使用加密的Realm。

##获得帮助

模型

Realm数据模型定义非常类似于传统的Java Bean。只需要继承自RealmObject类,Realm的注解处理器(Annotation processor)会自动生成代理类。

public class User extends RealmObject {

    @PrimaryKey
    private String          name;
    private int             age;

    @Ignore
    private int             sessionId;

    // Standard getters & setters generated by your IDE…
    public String getName() { return name; }
    public void   setName(String name) { this.name = name; }
    public int    getAge() { return age; }
    public void   setAge(int age) { this.age = age; }
    public int    getSessionId() { return sessionId; }
    public void   setSessionId(int sessionId) { this.sessionId = sessionId; }
}

请注意,RealmObject子类的getter和setter会被生成的代理类重载,您添加到getter和setter的任何自定义逻辑实际上并不会被执行。

字段类型

Realm支持以下字段类型:booleanbyteshortintlongfloatdoubleStringDatebyte []。整数类型shortintlong都被映射到realm内的相同类型(实际上为long)。再者,还可以使用RealmObject的子类和RealmList<? extends RealmObject>来表示模型关系。

Realm对象中还可以声明包装类型(boxed type)属性,包括:BooleanByteShortIntegerLongFloatDouble。通过使用包装类型,可以使这些属性存取空值(null)。

@Required修饰类型和空值(null)

某些时候,空值(null)对于属性并不合适。这时可以使用注解@Required告诉Realm强制禁止空值(null)被存储。基本数据类型(primitive types)不需要使用注解@Required,因为他们本身就不可为空。

忽略的属性

注解@Ignore意味着一个字段不应该被保存到Realm。某些时候输入的信息包含比模型更多的字段,而您不希望处理这些未使用的数据字段,您可以用@Ignore来标识这些您希望被Realm忽略的字段。

索引(Index)属性

注解@Index会为字段增加搜索索引。这会导致插入速度变慢,同时数据文件体积有所增加,但能加速查询。因此建议仅在需要加速查询时才添加索引。目前仅支持索引的属性类型包括:StringbyteshortintlongbooleanDate

主键

@PrimaryKey可以用来定义字段为主键,该字段类型必须为字符串或整数(shortintlong)。不可以存在多个主键。使用支持索引的属性类型作为主键同时意味着为该字段建立索引。

当创建Realm对象时,所有字段会被设置为默认值。为了避免与具有相同主键的另一个对象冲突,建议创建一个standalone对象,为字段的赋值,然后用copyToRealm()方法将该对象复制到Realm。

主键的存在意味着可以使用createOrUpdate()方法,它会用此主键尝试寻找一个已存在的对象,如果对象存在,就更新该对象;反之,它会创建一个新的对象。

使用主键会对性能产生影响。创建和更新对象将会慢一点,而查询则会变快。很难量化这些性能的差异,因为性能的改变跟您数据库的大小息息相关。

Realm.createObject()会返回一个所有字段被设置为默认值的新对象。如果该模型类存在主键,那么有可能返回对象的主键的默认值与其它已存在的对象冲突。建议创建一个独立的(standalone)Realm对象,并给其主键赋值,然后调用copyToRealm()来避免冲突。

MyObject obj = new MyObject();
obj.setId(42);
obj.setName("Fish");
realm.beginTransaction();
// This will create a new one in Realm
// realm.copyToRealm(obj);
// This will update a existing one with the same id or create a new one instead
realm.copyToRealmOrUpdate(obj);
realm.commitTransaction();
'''

主键不可被赋予空值(null),使用`@PrimaryKey`时即同时隐式声明了`@Required`。

### 限制

由于Realm会使用代理类重载模型类中的gettersetter[模型类中允许的内容会有一些限制](#section-31)

## 写入

在任何时间都可以对对象进行访问和查询(读取事务是隐式的)。
所有的写操作(添加、修改和删除对象),必须包含在写入事务(transaction)中。写入事务可以提交或取消。在提交期间,所有更改都将被写入磁盘,并且,只有当所有更改可以被持久化时,提交才会成功。通过取消一个写入事务,所有更改将被丢弃。使用写入事务,会确保您的数据的一致性。

写入事务也用于确保线程安全:

<pre class="highlight java"><code><span class="c1">// Obtain a Realm instance</span>
<span class="n">Realm</span> <span class="n">realm</span> <span class="o">=</span> <span class="n">Realm</span><span class="o">.</span><span class="na">getInstance</span><span class="o">(</span><span class="k">this</span><span class="o">);</span>

<span class="n">realm</span><span class="o">.</span><span class="na">beginTransaction</span><span class="o">();</span>

<span class="c1">//... add or update objects here ...</span>

<span class="n">realm</span><span class="o">.</span><span class="na">commitTransaction</span><span class="o">();</span></code></pre>


当您在写入事务内处理Realm对象时,您可能会遇到想要放弃更改的情况。您可以简单地取消写入事务:

<pre class="highlight java"><code><span class="n">realm</span><span class="o">.</span><span class="na">beginTransaction</span><span class="o">();</span>
<span class="n">User</span> <span class="n">user</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">createObject</span><span class="o">(</span><span class="n">User</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>

<span class="c1">//  ... </span>

<span class="n">realm</span><span class="o">.</span><span class="na">cancelTransaction</span><span class="o">();</span></code></pre>


请注意,写入事务之间会互相阻塞,如果一个写入事务正在进行,那么其他的线程的写入事务就会阻塞它们所在的线程。同时在UI线程和后台线程使用写入事务有可能导致ANR问题。可以使用 [异步事务(async transactions)](/docs/java/latest/api/io/realm/Realm.html#executeTransaction-io.realm.Realm.Transaction-io.realm.Realm.Transaction.Callback-)以避免阻塞 UI 线程。

由但得益于 Realm 的 MVCC 架构,当正在进行一个写入事务时读取操作并不会被阻塞!这意味着,除非您需要从多个线程进行并发写入操作,否则,您可以尽量使用更大的写入事务来做更多的事情而不是使用多个更小的写入事务。当写入事务被提交到Realm时,该Realm的所有其他实例都将被通知,读入隐式事务将自动刷新您每个Realm对象。

在Realm中的读写访问是符合[ACID](http://en.wikipedia.org/wiki/ACID)的.

### 创建对象

由于Realm对象都强依赖于Realm,它们应该直接通过Realm被实例化:

<pre class="highlight java"><code><span class="n">realm</span><span class="o">.</span><span class="na">beginTransaction</span><span class="o">();</span>
<span class="n">User</span> <span class="n">user</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">createObject</span><span class="o">(</span><span class="n">User</span><span class="o">.</span><span class="na">class</span><span class="o">);</span> <span class="c1">// Create a new object</span>
<span class="n">user</span><span class="o">.</span><span class="na">setName</span><span class="o">(</span><span class="s">"John"</span><span class="o">);</span>
<span class="n">user</span><span class="o">.</span><span class="na">setEmail</span><span class="o">(</span><span class="s">"john@corporation.com"</span><span class="o">);</span>
<span class="n">realm</span><span class="o">.</span><span class="na">commitTransaction</span><span class="o">();</span></code></pre>


或者您可以先创建一个对象的实例,并在之后使用[realm.copyToRealm()](api/io/realm/Realm.html#copyToRealm(E)) 添加。Realm对象支持多个构造函数,只要其中之一是[公共无参数构造函数](http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html)即可。

<pre class="highlight java"><code><span class="n">User</span> <span class="n">user</span> <span class="o">=</span> <span class="k">new</span> <span class="n">User</span><span class="o">(</span><span class="s">"John"</span><span class="o">);</span>
<span class="n">user</span><span class="o">.</span><span class="na">setEmail</span><span class="o">(</span><span class="s">"john@corporation.com"</span><span class="o">);</span>

<span class="c1">// Copy the object to Realm. Any further changes must happen on realmUser</span>
<span class="n">realm</span><span class="o">.</span><span class="na">beginTransaction</span><span class="o">();</span>
<span class="n">User</span> <span class="n">realmUser</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">copyToRealm</span><span class="o">(</span><span class="n">user</span><span class="o">);</span>  
<span class="n">realm</span><span class="o">.</span><span class="na">commitTransaction</span><span class="o">();</span></code></pre>


当使用`realm.copyToRealm()`时,请注意只有返回的对象是由Realm管理的,这非常重要。对原始对象(Standalone Object)的任何改变都不会写入Realm.

### 事务执行块(Transaction blocks)

除手动调用`realm.beginTransaction()`、`realm.commitTransaction()`和`realm.cancelTransaction()`之外你可以使用[realm.executeTransaction()](api/io/realm/Realm.html#executeTransaction(io.realm.Realm Transaction))方法,它会自动处理写入事物的开始和提交,并在错误发生时取消写入事物。

<pre class="highlight java"><code><span class="n">realm</span><span class="o">.</span><span class="na">executeTransaction</span><span class="o">(</span><span class="k">new</span> <span class="n">Realm</span><span class="o">.</span><span class="na">Transaction</span><span class="o">()</span> <span class="o">{</span>
	<span class="nd">@Override</span>
	<span class="kd">public</span> <span class="kt">void</span> <span class="nf">execute</span><span class="o">(</span><span class="n">Realm</span> <span class="n">realm</span><span class="o">)</span> <span class="o">{</span>
		<span class="n">User</span> <span class="n">user</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">createObject</span><span class="o">(</span><span class="n">User</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
		<span class="n">user</span><span class="o">.</span><span class="na">setName</span><span class="o">(</span><span class="s">"John"</span><span class="o">);</span>
		<span class="n">user</span><span class="o">.</span><span class="na">setEmail</span><span class="o">(</span><span class="s">"john@corporation.com"</span><span class="o">);</span>
	<span class="o">}</span>
<span class="o">});</span></code></pre>


### 异步事务(Asynchronous Transactions)

事务会相互阻塞其所在的线程,在后台线程中开启事务进行写入操作可以有效避免UI线程被阻塞。通过使用异步事务,Realm会在后台线程中进行写入操作,并在事务完成时将结果传回调用线程。

添加`Realm.Transaction.Callback`调用参数即可将一个同步事务转换成一个异步事务。

```java
realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm bgRealm) {
                User user = bgRealm.createObject(User.class);
                user.setName("John");
                user.setEmail("john@corporation.com");
            }
        }, new Realm.Transaction.Callback() {
            @Override
            public void onSuccess() {
            }

            @Override
            public void onError(Exception e) {
                // transaction is automatically rolled-back, do any cleanup here
            }
        });
'''

回调函数体并不是必须重载的,重载了的回调函数会在事务成功或者失败时在被调用发生的线程执行。回调函数是通过`Looper`被执行的,所以在非`Looper`线程中只有空(`null`)回调函数被允许使用。

```java
RealmAsyncTask transaction = realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm bgRealm) {
                User user = bgRealm.createObject(User.class);
                user.setName("John");
                user.setEmail("john@corporation.com");
            }
        }, null);
'''

异步事务调用会返回一个`RealmAsyncTask`对象。当你退出Activity或者Fragment时可以使用该对象取消异步事务。如果你在回调函数中更新UI,那么忘记取消异步事务可能会造成你的app崩溃。

```java
public void onStop () {
    if (transaction != null && !transaction.isCancelled()) {
        transaction.cancel();
    }
}
'''

## 查询

<div class="alert alert-info">
Realm 中的所有读取(包括查询)操作都是延迟执行的,且数据绝不会被拷贝。
</div>

Realm的查询引擎使用[Fluent interface](https://en.wikipedia.org/wiki/Fluent_interface)来构造多条件查询。

使用 User 类 -

<pre class="highlight java"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">User</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>

    <span class="nd">@PrimaryKey</span>
    <span class="kd">private</span> <span class="n">String</span>          <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kt">int</span>             <span class="n">age</span><span class="o">;</span>

    <span class="nd">@Ignore</span>
    <span class="kd">private</span> <span class="kt">int</span>             <span class="n">sessionId</span><span class="o">;</span>

    <span class="c1">// Standard getters &amp; setters generated by your IDE…</span>
    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getName</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">name</span><span class="o">;</span> <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">void</span>   <span class="nf">setName</span><span class="o">(</span><span class="n">String</span> <span class="n">name</span><span class="o">)</span> <span class="o">{</span> <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span> <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">int</span>    <span class="nf">getAge</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">age</span><span class="o">;</span> <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">void</span>   <span class="nf">setAge</span><span class="o">(</span><span class="kt">int</span> <span class="n">age</span><span class="o">)</span> <span class="o">{</span> <span class="k">this</span><span class="o">.</span><span class="na">age</span> <span class="o">=</span> <span class="n">age</span><span class="o">;</span> <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">int</span>    <span class="nf">getSessionId</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">sessionId</span><span class="o">;</span> <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">void</span>   <span class="nf">setSessionId</span><span class="o">(</span><span class="kt">int</span> <span class="n">sessionId</span><span class="o">)</span> <span class="o">{</span> <span class="k">this</span><span class="o">.</span><span class="na">sessionId</span> <span class="o">=</span> <span class="n">sessionId</span><span class="o">;</span> <span class="o">}</span>
<span class="o">}</span></code></pre>


比如查找所有叫做John或Peter的用户,您可以这么写:

<pre class="highlight java"><code><span class="c1">// Build the query looking at all users:</span>
<span class="n">RealmQuery</span><span class="o">&lt;</span><span class="n">User</span><span class="o">&gt;</span> <span class="n">query</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">where</span><span class="o">(</span><span class="n">User</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>

<span class="c1">// Add query conditions:</span>
<span class="n">query</span><span class="o">.</span><span class="na">equalTo</span><span class="o">(</span><span class="s">"name"</span><span class="o">,</span> <span class="s">"John"</span><span class="o">);</span>
<span class="n">query</span><span class="o">.</span><span class="na">or</span><span class="o">().</span><span class="na">equalTo</span><span class="o">(</span><span class="s">"name"</span><span class="o">,</span> <span class="s">"Peter"</span><span class="o">);</span>

<span class="c1">// Execute the query:</span>
<span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">User</span><span class="o">&gt;</span> <span class="n">result1</span> <span class="o">=</span> <span class="n">query</span><span class="o">.</span><span class="na">findAll</span><span class="o">();</span>

<span class="c1">// Or alternatively do the same all at once (the "Fluent interface"):</span>
<span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">User</span><span class="o">&gt;</span> <span class="n">result2</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">where</span><span class="o">(</span><span class="n">User</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
                                  <span class="o">.</span><span class="na">equalTo</span><span class="o">(</span><span class="s">"name"</span><span class="o">,</span> <span class="s">"John"</span><span class="o">)</span>
                                  <span class="o">.</span><span class="na">or</span><span class="o">()</span>
                                  <span class="o">.</span><span class="na">equalTo</span><span class="o">(</span><span class="s">"name"</span><span class="o">,</span> <span class="s">"Peter"</span><span class="o">)</span>
                                  <span class="o">.</span><span class="na">findAll</span><span class="o">();</span></code></pre>


查询返回一个`RealmResults`实例,其中包含名叫 John 和 Peter 的用户。这些对象并非拷贝,也就是说你得到的是一个匹配对象引用的列表,你对匹配对象所有的操作都是直接施加于它的原始对象。`RealmResults`继承自Java的`AbstractList`,行为类似。例如你可以通过index来访问其中的某个对象。

当查询没有任何匹配时,返回的RealmResults对象将不会为`null`,取而代之的是它的[`size()`](api/io/realm/RealmResults.html#size())方法将返0。

修改或删除`RealmResults`中任何一个对象都必须在写入事务中完成。

### 按类型检索对象

从Realm中检索对象的最基本方法是[`realm.allObjects()`](api/io/realm/Realm.html#allObjects),它返回了包含被查询模型类的所有对象的`RealmResults`。

另外还有提供排序功能的`allObjects()`。参见 [`realm.allObjectsSorted()`](api/io/realm/Realm.html#allObjectsorted)了解详情。


### 查询条件

Realm支持以下查询条件:

- `between`、`greaterThan()`、`lessThan()`、`greaterThanOrEqualTo()`和`lessThanOrEqualTo()`
- `equalTo()`和`notEqualTo()`
- `contains()`、`beginsWith()`和`endsWith()`

并非所有条件都适用于所有数据类型,具体请参考[`RealmQuery` API](api/io/realm/RealmQuery.html)。

### 修饰符

字符串查询条件可以通过使用`CASE_INSENSITIVE`修饰符来忽略字母A-Z和a-z的大小写。

### 逻辑运算符

每个查询条件都会被被隐式地被`逻辑和(&)`组合在一起,而`逻辑或(or)`需要显式地去执行`or()`。

使用 User 类 -
<pre class="highlight java"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">User</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>

    <span class="nd">@PrimaryKey</span>
    <span class="kd">private</span> <span class="n">String</span>          <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kt">int</span>             <span class="n">age</span><span class="o">;</span>

    <span class="nd">@Ignore</span>
    <span class="kd">private</span> <span class="kt">int</span>             <span class="n">sessionId</span><span class="o">;</span>

    <span class="c1">// Standard getters &amp; setters generated by your IDE…</span>
    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getName</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">name</span><span class="o">;</span> <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">void</span>   <span class="nf">setName</span><span class="o">(</span><span class="n">String</span> <span class="n">name</span><span class="o">)</span> <span class="o">{</span> <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span> <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">int</span>    <span class="nf">getAge</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">age</span><span class="o">;</span> <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">void</span>   <span class="nf">setAge</span><span class="o">(</span><span class="kt">int</span> <span class="n">age</span><span class="o">)</span> <span class="o">{</span> <span class="k">this</span><span class="o">.</span><span class="na">age</span> <span class="o">=</span> <span class="n">age</span><span class="o">;</span> <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">int</span>    <span class="nf">getSessionId</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">sessionId</span><span class="o">;</span> <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">void</span>   <span class="nf">setSessionId</span><span class="o">(</span><span class="kt">int</span> <span class="n">sessionId</span><span class="o">)</span> <span class="o">{</span> <span class="k">this</span><span class="o">.</span><span class="na">sessionId</span> <span class="o">=</span> <span class="n">sessionId</span><span class="o">;</span> <span class="o">}</span>
<span class="o">}</span></code></pre>


你也可以将查询条件组合在一起,使用`beginGroup()`(相当于左括号)和`endGroup()`(相当于右括号):

<pre class="highlight java"><code><span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">User</span><span class="o">&gt;</span> <span class="n">r</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">where</span><span class="o">(</span><span class="n">User</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
                            <span class="o">.</span><span class="na">greaterThan</span><span class="o">(</span><span class="s">"age"</span><span class="o">,</span> <span class="mi">10</span><span class="o">)</span>  <span class="c1">//implicit AND</span>
                            <span class="o">.</span><span class="na">beginGroup</span><span class="o">()</span>
                                <span class="o">.</span><span class="na">equalTo</span><span class="o">(</span><span class="s">"name"</span><span class="o">,</span> <span class="s">"Peter"</span><span class="o">)</span>
                                <span class="o">.</span><span class="na">or</span><span class="o">()</span>
                                <span class="o">.</span><span class="na">contains</span><span class="o">(</span><span class="s">"name"</span><span class="o">,</span> <span class="s">"Jo"</span><span class="o">)</span>
                            <span class="o">.</span><span class="na">endGroup</span><span class="o">()</span>
                            <span class="o">.</span><span class="na">findAll</span><span class="o">();</span></code></pre>


此外,也可以用`not()`否定一个条件。该`not()`运算符可以与`beginGroup()`/`endGroup()` 一起使用来否定子条件。


### 排序

当你执行完查询获得结果后,可以对它进行排序:

```java
RealmResults<User> result = realm.where(User.class).findAll();
result.sort("age"); // Sort ascending
result.sort("age", Sort.DESCENDING);
'''

### 链式查询

因为查询结果并不会被复制,且在查询提交时并不会被执行,您可以链式串起查询并逐步进行分类筛选:

<pre class="highlight java"><code><span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;</span> <span class="n">teenagers</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">where</span><span class="o">(</span><span class="n">Person</span><span class="o">.</span><span class="na">class</span><span class="o">).</span><span class="na">between</span><span class="o">(</span><span class="s">"age"</span><span class="o">,</span> <span class="mi">13</span><span class="o">,</span> <span class="mi">20</span><span class="o">).</span><span class="na">findAll</span><span class="o">();</span>
<span class="n">Person</span> <span class="n">firstJohn</span> <span class="o">=</span> <span class="n">teenagers</span><span class="o">.</span><span class="na">where</span><span class="o">().</span><span class="na">equalTo</span><span class="o">(</span><span class="s">"name"</span><span class="o">,</span> <span class="s">"John"</span><span class="o">).</span><span class="na">findFirst</span><span class="o">();</span></code></pre>


### 聚合

RealmResult 自带一些聚合方法:

<pre class="highlight java"><code><span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">User</span><span class="o">&gt;</span> <span class="n">results</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">where</span><span class="o">(</span><span class="n">User</span><span class="o">.</span><span class="na">class</span><span class="o">).</span><span class="na">findAll</span><span class="o">();</span>
<span class="kt">long</span>   <span class="n">sum</span>     <span class="o">=</span> <span class="n">results</span><span class="o">.</span><span class="na">sum</span><span class="o">(</span><span class="s">"age"</span><span class="o">).</span><span class="na">longValue</span><span class="o">();</span>
<span class="kt">long</span>   <span class="n">min</span>     <span class="o">=</span> <span class="n">results</span><span class="o">.</span><span class="na">min</span><span class="o">(</span><span class="s">"age"</span><span class="o">).</span><span class="na">longValue</span><span class="o">();</span>
<span class="kt">long</span>   <span class="n">max</span>     <span class="o">=</span> <span class="n">results</span><span class="o">.</span><span class="na">max</span><span class="o">(</span><span class="s">"age"</span><span class="o">).</span><span class="na">longValue</span><span class="o">();</span>
<span class="kt">double</span> <span class="n">average</span> <span class="o">=</span> <span class="n">results</span><span class="o">.</span><span class="na">average</span><span class="o">(</span><span class="s">"age"</span><span class="o">);</span>

<span class="kt">long</span>   <span class="n">matches</span> <span class="o">=</span> <span class="n">results</span><span class="o">.</span><span class="na">size</span><span class="o">();</span></code></pre>


### 迭代

可以这样遍历`RealmResults`:

<pre class="highlight java"><code><span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">User</span><span class="o">&gt;</span> <span class="n">results</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">where</span><span class="o">(</span><span class="n">User</span><span class="o">.</span><span class="na">class</span><span class="o">).</span><span class="na">findAll</span><span class="o">();</span>
<span class="k">for</span> <span class="o">(</span><span class="n">User</span> <span class="n">u</span> <span class="o">:</span> <span class="n">results</span><span class="o">)</span> <span class="o">{</span>
    <span class="c1">// ... do something with the object ...</span>
<span class="o">}</span></code></pre>


或者使用`for`循环:

<pre class="highlight java"><code><span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">User</span><span class="o">&gt;</span> <span class="n">results</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">where</span><span class="o">(</span><span class="n">User</span><span class="o">.</span><span class="na">class</span><span class="o">).</span><span class="na">findAll</span><span class="o">();</span>
<span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">results</span><span class="o">.</span><span class="na">size</span><span class="o">();</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
    <span class="n">User</span> <span class="n">u</span> <span class="o">=</span> <span class="n">results</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">i</span><span class="o">);</span>
    <span class="c1">// ... do something with the object ...</span>
<span class="o">}</span></code></pre>


### 删除

你可以从查询结果中删除数据:

<pre class="highlight java"><code><span class="c1">// obtain the results of a query</span>
<span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">Dog</span><span class="o">&gt;</span> <span class="n">results</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">where</span><span class="o">(</span><span class="n">Dog</span><span class="o">.</span><span class="na">class</span><span class="o">).</span><span class="na">findAll</span><span class="o">();</span>

<span class="c1">// All changes to data must happen in a transaction</span>
<span class="n">realm</span><span class="o">.</span><span class="na">beginTransaction</span><span class="o">();</span>

<span class="c1">// remove single match</span>
<span class="n">results</span><span class="o">.</span><span class="na">remove</span><span class="o">(</span><span class="mi">0</span><span class="o">);</span>
<span class="n">results</span><span class="o">.</span><span class="na">removeLast</span><span class="o">();</span>

<span class="c1">// remove a single object</span>
<span class="n">Dog</span> <span class="n">dog</span> <span class="o">=</span> <span class="n">results</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="mi">5</span><span class="o">);</span>
<span class="n">dog</span><span class="o">.</span><span class="na">removeFromRealm</span><span class="o">();</span>

<span class="c1">// Delete all matches</span>
<span class="n">results</span><span class="o">.</span><span class="na">clear</span><span class="o">();</span>

<span class="n">realm</span><span class="o">.</span><span class="na">commitTransaction</span><span class="o">()</span></code></pre>


### 异步查询(Asynchronous Queries)

可以使用后台线程进行查询。

Realm的大部分查询都非常快——快到可以使用在UI线程中而感觉不到延迟。但如果需要进行非常复杂的查询或者在大量数据中进行查询,那么使用后台线程进行查询将会是一个不错的主意。

示例:查找名字为"John"或者"Peter"的用户。

#### 创建异步查询

```java
RealmResults<User> result = realm.where(User.class)
                              .equalTo("name", "John")
                              .or()
                              .equalTo("name", "Peter")
                              .findAllAsync();
'''

请注意,这里的调用并不会阻塞,而是立即返回一个`RealmResults<User>`。这很类似于标准Java中[Future](http://developer.android.com/reference/java/util/concurrent/Future.html)的概念。查询将会在后台线程中被执行,当其完成时,之前返回的`RealmResults`实例会被更新。

如果你希望当查询完成、`RealmResults`被更新时获得通知,你可以注册一个`RealmChangeListener`。这个监听器会在`RealmResults`被更新时被调用(通常是在事务被提交后)。

#### 注册回调

```java
private RealmChangeListener callback = new RealmChangeListener() {
    @Override
    public void onChange() { // called once the query complete and on every update
    // use the result
    }
};

public void onStart() {
    RealmResults<User> result = realm.where(User.class).findAllAsync();
    result.addChangeListener(callback);
}
'''

请在退出Activity或者Fragment时移除监听器的注册以避免内存泄漏。

```java
public void onStop () {
    result.removeChangeListener(callback); // remove a particular listener
    // or
    result.removeChangeListeners(); // remove all registered listeners
}
'''

#### 检查查询是否完成

```java
RealmResults<User> result = realm.where(User.class).findAllAsync();
if (result.isLoaded()) {
  // Results are now available
}
'''

同步查询返回的`RealmResults`实例的`isLoaded`方法会永远返回`true`。

#### 强制装载异步查询

你可以选择性地等待异步查询完成,而这将会阻塞当前线程,使查询变成同步(与[Future.get()](http://developer.android.com/reference/java/util/concurrent/Future.html#get())类似的概念)。

```java
RealmResults<User> result = realm.where(User.class).findAllAsync();
result.load() // be careful, this will block the current thread until it returns
'''

#### 非Looper线程

你可以在Looper线程中使用异步查询。异步查询需要是哟功能Realm的[Handler](http://developer.android.com/reference/android/os/Handler.html)来传递查询结果。在没有[Looper](http://developer.android.com/reference/android/os/Looper.html)的线程中使用异步查询会导致`IllegalStateException`异常被抛出。

## Realms

Realm(s)是我们对数据库的称谓:它包含多个不同的对象,并对应磁盘中的一个文件。

### 默认的Realm

您可能已经注意到,我们总是通过`Realm.getInstance(this)`来访问我们已初始化的realm变量。该静态方法会为你的当前线程返回一个Realm实例,它对应了您`Context.getFilesDir()`目录中的`default.realm`文件。

该文件位于您应用的可写根目录中。默认情况下的Realm使用内部存储(internal storage),您的应用并不需要取得任何读写权限。一般来说,这个文件位于`/data/data/<packagename>/files/`。

您可以通过`realm.getPath()`来获得该Realm的绝对路径。

请务必注意到Realm的实例是线程单例化的,也就是说,在同一个线程内多次调用静态方法获得针对同路径的Realm,会返回同一个Realm实例。

### 配置Realm

您可以通过`Realm.getInstance(context)`非常方便地开始使用Realm。但如果您有更多的需求,通过创建一个[`RealmConfiguration`](api/io/realm/RealmConfiguration.html),您可以控制有关Realm的更多细节。

```java
// The RealmConfiguration is created using the builder pattern.
RealmConfiguration config = new RealmConfiguration.Builder(context)
  .name("myrealm.realm")
  .encryptionKey(getKey())
  .schemaVersion(42)
  .setModules(new MySchemaModule())
  .migration(new MyMigration())
  .build();

// These two are equivalent
Realm realm = Realm.getInstance(context);
Realm realm = Realm.getInstance(new RealmConfiguration.Builder(context).build());
'''

`RealmConfiguration`可以保存为默认配置。通过在自定义的[Application](http://developer.android.com/reference/android/app/Application.html)设置默认的Realm配置,可以使您在代码中的其他地方更加方便地创建针对该默认配置的Realm。

```java
public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    RealmConfiguration config = new RealmConfiguration.Builder(context).build();
    Realm.setDefaultConfiguration(config);
  }
}

public class MyActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Realm realm = Realm.getDefaultInstance();
  }
}
'''

您还可以有多个`RealmConfiguration`。如此,您便可以控制Realm的版本、结构(schema)和路径。

```java
RealmConfiguration myConfig = new RealmConfiguration.Builder(context)
  .name("myrealm.realm").
  .schemaVersion(2)
  .setModules(new MyCustomSchema())
  .build();

RealmConfiguration otherConfig = new RealmConfiguration.Builder(context)
  .name("otherrealm.realm")
  .schemaVersion(5)
  .setModules(new MyOtherSchema())
  .build();

Realm myRealm = Realm.getInstance(myConfig);
Realm otherRealm = Realm.getInstance(otherConfig);
'''

### In-Memory Realm

定义一个非持久化的、存在于内存中的Realm实例:

```java
RealmConfiguration myConfig = new RealmConfiguration.Builder(context)
    .name("myrealm.realm")
    .inMemory()
    .build();
'''

这样就可以创建一个存在于“内存中的”Realm。“内存中的”Realm在内存紧张的情况下仍有可能使用到磁盘存储,但是这些磁盘空间都会在Realm实例完全关闭的时候被释放。

请注意使用同样的名称同时创建“内存中的”Realm和常规的(持久化)Realm是不允许的。

当某个“内存中的”Realm的所有实例引用都被释放,该Realm下的数据也同时会被清除。建议在您的app生命周期中保持对“内存中的”Realm实例的引用以避免非期望的数据丢失。

### Dynamic Realm

对于普通的`Realm`来说,数据模型被定义成了`RealmObject`的子类。这样做保证了类型安全,但有时候某些数据模型在编译期是无法获得的。例如在处理数据迁移(migration)或CSV文件的时候。

[`DynamicRealm`](api/io/realm/DynamicRealm.html)是普通Realm的一个变种。它可以在没有`RealmObject`子类的情况下操作Realm数据。其对数据的访问是基于字符串而非`RealmObject`的定义。

创建Dynamic Realm使用与创建普通Realm相同的`RealmConfiguration`,但是它的创建过程会忽略对schema、migration以及schema版本的检查。

```java
RealmConfiguration realmConfig = new RealmConfiguration.Builder(context).build();
DynamicRealm realm = DynamicRealm.getInstance(realmConfig);

// In a DynamicRealm all objects are DynamicRealmObjects
DynamicRealmObject person = realm.createObject("Person");

// All fields are accessed using strings
String name = person.getString("name");
int age = person.getInt("age");

// An underlying schema still exists, so accessing a field that does not exist
// will throw an exception
person.getString("I don't exist");

// Queries stil work normally
RealmResults<DynamicRealmObject> persons = realm.where("Person")
    .equalTo("name", "John")
    .findAll();

DynamicRealm以类型安全和性能为代价,换来了更多的灵活性。请在你确实需要这些灵活性的情况下使用。

跨线程使用Realm

请谨记:Realm、RealmObject和RealmResults实例都不可以跨线程使用。但是您可以使用异步查询异步事务来将部分操作放入后台线程进行,待完成时调用线程被通知以获取结果。

当您需要跨线程访问同一部分数据时,只需简单地在该线程重新获取一个Realm实例(例如:Realm.getInstance(RealmConfiguration config)或是其他类似方法),然后通过这个Realm实例来查询获得您需要的数据。查询获得的对象会映射到Realm中的相同数据,由此方法获得对象在其线程中任何地方都可读写!

关闭Realm实例

Realm实现了Closeable接口以便与释放native内存和文件描述符,请务必在使用完毕后关闭Realm实例。

Realm实例是基于引用计数的, 也就是说假设您在同一个线程中调用了getInstance()两次,您需要同样调用close()两次以关闭该实例。举例来说,如果您需要实现Runnable,简单地在函数开始的时候调用getInstance(),在函数结束的时候调用close()即可!

对于UI线程,您可以选择在onDestroy()方法内调用realm.close()

对于AsyncTask,这里有个不错的例子可以参考:

protected Long doInBackground(Context... contexts) {
    Realm realm = null;
    try {
        realm = Realm.getInstance(contexts[0]);

        // ... Use the Realm instance
    } finally {
        if (realm != null) {
            realm.close();
        }
    }
}

如果您需要创建一个包含Looper的线程,可以参考这个:

public class MyThread extends Thread {
    private final Context;

    public MyThread(Context context) {
        this.context = context;
    }

    public void run() {
        Looper.prepare();
        Realm realm = null;
        try {
            realm = Realm.getInstance(context);

            //... Setup the handlers using the Realm instance
            Lopper.loop();
        } finally {
            if (realm != null) {
                realm.close();
            }
        }
    }
}

如果您很幸运地工作在minSdkVersion >= 19之下,可以使用try-with-resources

try (Realm realm = Realm.getInstance(context)) {
	// No need to close the Realm instance manually
}

自动更新(Auto-Refresh)

如果Realm实例存在于一个带有Looper的线程,那么这个Realm实例即具有自动更新的功能。这意味这如果发生了Realm数据库的变化,那么该Realm实例会在下一个事件循环(event loop)中自动更新。这个便捷的功能使您不必花费太多的精力就能保证的UI与数据的实时同步。

如果Realm的实例所在线程没有绑定Looper,那么该实例不会被更新直到您手动调用refresh()方法。请注意,不更新Realm以保持对旧数据的引用会造成而外的磁盘和内存开销。这也是为什么要在线程结束时调用close()关闭Realm实例的一个重要原因。

如果您想确定当前Realm实例是否有自动更新功能,可以通过调用isAutoRefresh()方法查询。

查找Realm数据库文件

如果您想知道您应用的Realm文件的具体路径,请参见这个StackOverflow上的答案

Schemas

Realm使用所有项目中的Realm模型类来创建schema。但这个行为是可以改变的,例如,您可以通过使用RealmModule让Realm只包含所有模型类的一个子集。

// Create the module
@RealmModule(classes = { Person.class, Dog.class })
public class MyModule {
}

// Set the module in the RealmConfiguration to allow only classes defined by the module.
RealmConfiguration config = new RealmConfiguration.Builder(context)
  .setModules(new MyModule())
  .build();

// It is possible to combine multiple modules to one schema.
RealmConfiguration config = new RealmConfiguration.Builder(context)
  .setModules(new MyModule(), new MyOtherModule())
  .build();
'''


### 共享schemas

<div class="alert alert-info">
**库(library)开发者请注意:** 在库中使用到的Realm必须通过`RealmModule`来暴露和使用其schema。
</div>

这样可以防止库项目自动生成默认`RealmModule`从而避免和app生成的默认`RealmModule`冲突。库项目也是通过`RealmModule`来向app项目暴露自己的Realm模型类。

```java
// Library must create a module and set library = true. This will prevent the default
// module from being created.
// allClasses = true can be used instead of listing all classes in the library.
@RealmModule(library = true, allClasses = true)
public class MyLibraryModule {
}

// Library projects are therefore required to explicitly set their own module.
RealmConfiguration libraryConfig = new RealmConfiguration.Builder(context)
  .name("library.realm")
  .setModules(new MyLibraryModule())
  .build();

// Apps can add the library RealmModule to their own schema.
RealmConfiguration config = new RealmConfiguration.Builder(context)
  .name("app.realm")
  .setModules(Realm.getDefaultModule(), new MyLibraryModule())
  .build();
'''

这里有一个[如何使用在库和app项目间使用`RealmModule`的完整例子](https://github.com/realm/realm-java/tree/master/examples/realmModuleExample)。

## 关系

任意两个`RealmObject`可以相互关联。

<pre class="highlight java"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Email</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">address</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kt">boolean</span> <span class="n">active</span><span class="o">;</span>
    <span class="c1">// ... setters and getters left out</span>
<span class="o">}</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Contact</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">Email</span> <span class="n">email</span><span class="o">;</span>
    <span class="c1">// ... setters and getters left out</span>
<span class="o">}</span></code></pre>


`RealmObject`之间的关联总体来说并不怎么消耗系统开销。Realm对关系对象的处理非常高效并且节约内存。

### 多对一

您只需要简单地声明一个Realm模型类的属性即可:

<pre class="highlight java"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Contact</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">Email</span> <span class="n">email</span><span class="o">;</span>
    <span class="c1">// Other fields…</span>
<span class="o">}</span></code></pre>


每个Contact对象都有0或1个Email对象。在Realm中,您可以任意在多个Contact对象中使用同一个Email对象。同理,这个例子也解释了怎样实现一对一关系。

设置一个类型为`RealmObject`的属性为空值(null)会清除该属性的引用,但并不会删除对应的`RealmObject`。

### 多对多

您可以通过使用`RealmList`为一个对象关联0或多个其它对象。

<pre class="highlight java"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Contact</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">RealmList</span><span class="o">&lt;</span><span class="n">Email</span><span class="o">&gt;</span> <span class="n">emails</span><span class="o">;</span>
    <span class="c1">// Other fields…</span>
<span class="o">}</span></code></pre>


`RealmList`是Realm模型对象的容器,其行为与Java的普通`List`近乎一样。同一个Realm模型对象可以存在于多个`RealmList`中。同一个Realm模型对象可以在同一个`RealmList`中存在多次。您可以使用`RealmList`来表现一对多核多对多的数据关系。

使用 Contact 和 Email 类:
<pre class="highlight java"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Email</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">address</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kt">boolean</span> <span class="n">active</span><span class="o">;</span>
    <span class="c1">// ... setters and getters left out</span>
<span class="o">}</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Contact</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">Email</span> <span class="n">email</span><span class="o">;</span>
    <span class="c1">// ... setters and getters left out</span>
<span class="o">}</span></code></pre>


您可以通过标准的getter和setter来访问`RealmList`.

<pre class="highlight java"><code><span class="n">realm</span><span class="o">.</span><span class="na">beginTransaction</span><span class="o">();</span>
<span class="n">Contact</span> <span class="n">contact</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">createObject</span><span class="o">(</span><span class="n">Contact</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="n">contact</span><span class="o">.</span><span class="na">setName</span><span class="o">(</span><span class="s">"John Doe"</span><span class="o">);</span>

<span class="n">Email</span> <span class="n">email1</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">createObject</span><span class="o">(</span><span class="n">Email</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="n">email1</span><span class="o">.</span><span class="na">setAddress</span><span class="o">(</span><span class="s">"john@example.com"</span><span class="o">);</span>
<span class="n">email1</span><span class="o">.</span><span class="na">setActive</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
<span class="n">contact</span><span class="o">.</span><span class="na">getEmails</span><span class="o">().</span><span class="na">add</span><span class="o">(</span><span class="n">email1</span><span class="o">);</span>

<span class="n">Email</span> <span class="n">email2</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">createObject</span><span class="o">(</span><span class="n">Email</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="n">email2</span><span class="o">.</span><span class="na">setNumber</span><span class="o">(</span><span class="s">"jd@example.com"</span><span class="o">);</span>
<span class="n">email2</span><span class="o">.</span><span class="na">setActive</span><span class="o">(</span><span class="kc">false</span><span class="o">);</span>
<span class="n">contact</span><span class="o">.</span><span class="na">getEmails</span><span class="o">().</span><span class="na">add</span><span class="o">(</span><span class="n">email2</span><span class="o">);</span>

<span class="n">realm</span><span class="o">.</span><span class="na">commitTransaction</span><span class="o">();</span></code></pre>


有时递归关系很有用,这在Realm是允许的。

<pre class="highlight java"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Person</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">RealmList</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;</span> <span class="n">friends</span><span class="o">;</span>
    <span class="c1">// Other fields…</span>
<span class="o">}</span></code></pre>


当然,在使用递归关系的时候,您要注意死循环的问题。Realm并不会检查RealmList的循环嵌套。

设置一个类型为`RealmList`的属性为空值(null)会清空该列表,即列表长度变为0。但并不会删除列表中的任何`RealmObject`。`RealmList`的获取器(getter)永不会返回null。其返回对象永远是一个`RealmList`实例,但其长度有可能为0。

### 关联查询(Link queries)

Realm支持关联查询。继续使用之前的例子,如果您希望找到所有Email的active状态为真的Contact对象,您可以:

<pre class="highlight java"><code><span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">Contact</span><span class="o">&gt;</span> <span class="n">contacts</span> <span class="o">=</span> <span class="n">realm</span><span class="o">.</span><span class="na">where</span><span class="o">(</span><span class="n">Contact</span><span class="o">.</span><span class="na">class</span><span class="o">).</span><span class="na">equalTo</span><span class="o">(</span><span class="s">"emails.active"</span><span class="o">,</span> <span class="kc">true</span><span class="o">).</span><span class="na">findAll</span><span class="o">();</span></code></pre>


首先,请注意`equalsTo`的`field`名称包含关联的路径,以“.”分隔。

以上的查询含义为“所有至少含有一个email为active状态的contact”。请务必注意,这里的返回的contact中,有可能包含active为假的email对象,因为在其`RealmList`列表中,其它的email的active为真。

另外,关联查询中的每个条件是单独评估的!查询的最终结果是多个关联查询结果的交集。如下这个例子返回的最终结果的每个contact都至少有1个active为真的email和一个active为假的email。

```java
RealmResults<Contact> contacts = realm.where(Contact.class).equalTo("emails.active", true).equalTo("emails.active", false).findAll();
'''

## JSON

您可以直接将JSON对象添加到Realm中,这些JSON对象可以是一个String、一个[JSONObject](http://developer.android.com/reference/org/json/JSONObject.html)或者是一个[InputStream](http://developer.android.com/reference/java/io/InputStream.html)。Realm会忽略JSON中存在但未定义在Realm模型类里的字段。单独对象可以通过[Realm.createObjectFromJson()](api/io/realm/Realm.html#createObjectFromJson-java.lang.Class-java.lang.String-)添加。对象列表可以通过[Realm.createAllFromJson()](api/io/realm/Realm.html#createAllFromJson-java.lang.Class-java.lang.String-)添加。

<pre class="highlight java"><code><span class="c1">// A RealmObject that represents a city</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">City</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">city</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kt">int</span> <span class="n">id</span><span class="o">;</span>
    <span class="c1">// getters and setters left out ...</span>
<span class="o">}</span>

<span class="c1">// Insert from a string</span>
<span class="n">realm</span><span class="o">.</span><span class="na">beginTransaction</span><span class="o">();</span>
<span class="n">realm</span><span class="o">.</span><span class="na">createObjectFromJson</span><span class="o">(</span><span class="n">City</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="s">"{ city: \"Copenhagen\", id: 1 }"</span><span class="o">);</span>
<span class="n">realm</span><span class="o">.</span><span class="na">commitTransaction</span><span class="o">();</span>

<span class="c1">// Insert multiple items using a InputStream</span>
<span class="n">InputStream</span> <span class="n">is</span> <span class="o">=</span> <span class="k">new</span> <span class="n">FileInputStream</span><span class="o">(</span><span class="k">new</span> <span class="n">File</span><span class="o">(</span><span class="s">"path_to_file"</span><span class="o">));</span>
<span class="n">realm</span><span class="o">.</span><span class="na">beginTransaction</span><span class="o">();</span>
<span class="k">try</span> <span class="o">{</span>
    <span class="n">realm</span><span class="o">.</span><span class="na">createAllFromJson</span><span class="o">(</span><span class="n">City</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="n">is</span><span class="o">);</span>
    <span class="n">realm</span><span class="o">.</span><span class="na">commitTransaction</span><span class="o">();</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">realm</span><span class="o">.</span><span class="na">cancelTransaction</span><span class="o">();</span>
<span class="o">}</span></code></pre>


Realm解析JSON时遵循如下规则:
* 使用包含空值(null)的JSON创建对象:
    * 对于非必须(可为空值的属性),设置其值为`null`;
    * 对于必须(不可为空值的属性),抛出异常;
* 使用包含空值(null)的JSON更新对象:
    * 对于非必须(可为空值的属性),设置其值为`null`;
    * 对于必须(不可为空值的属性),抛出异常;
* 使用不包含对应属性的JSON:
    * 该属性保持不变

## 通知(Notifications)

<div class="alert alert-warning">
从0.80.3开始,Realm内部使用`弱引用`来管理`RealmChangeListener`以避免可能的内存泄漏。请**不要**使用匿名`RealmChangeListener`当作`addListener`的传入参数。请自行维护对`RealmChangeListener`的引用直至您不再需要更新通知。
</div>

当后台线程向Realm添加数据,您的UI线程或者其它线程可以添加一个监听器来获取数据改变的通知。监听器在Realm数据改变的时候会被触发。

```java
public class MyActivity extends Activity {
    private Realm realm;
    // A reference to RealmChangeListener needs to be held to avoid being
    // removed by the garbage collector.
    private RealmChangeListener realmListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      realm = Realm.getDefaultInstance();
      reamlListener = new RealmChangeListener() {
        @Override
        public void onChange() {
            // ... do something with the updates (UI, etc.) ...
        }};
      realm.addChangeListener(realmListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Remove the listener.
        realm.removeChangeListener(realmListener);
        // Close the realm instance.
        realm.close();
    }
}
'''

您可以轻松移除所有监听器。

<pre class="highlight java"><code><span class="n">realm</span><span class="o">.</span><span class="na">removeAllChangeListeners</span><span class="o">();</span></code></pre>


## 迁移(Migrations)


所有数据库都要处理模型改变的情况。Realm的数据模型用标准Java对象来定义,改变数据模型只需要改变数据对象定义即可。

如果没有旧Realm数据文件存在,那么代码的改变即会反应到相应的Realm数据文件改变。但如果已经有旧版本的Realm数据文件存在,Realm会抛出异常提示数据库文件需要迁移。请在相应的[`RealmConfiguration`](api/io/realm/RealmConfiguration.html)设置schema版本和migration代码来正确处理并避免该异常抛出。

```java
RealmConfiguration config = new RealmConfiguration.Builder(context)
    .schemaVersion(2) // Must be bumped when the schema changes
    .migration(new MyMigration()) // Migration to run instead of throwing an exception
    .build()
'''

如上示例使得相应的migration代码在迁移需要的时候被自动执行。我们提供了相关API用来升级已保存的schema以及对应之前schema的数据。

```java
// Example migration adding a new class
RealmMigration migration = new RealmMigration() {
  @Override
  public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {

     // DynamicRealm exposes an editable schema
     RealmSchema schema = realm.getSchema();

     // Migrate to version 1: Add a new class
     // Example:
     // public Person extends RealmObject {
     //     private String name;
     //     private int age;
     //     // getters and setters left out for brevity
     // }
     if (oldVersion == 0) {
        schema.create("Person")
            .addField("name", String.class)
            .addField("age", int.class);
        oldVersion++;
     }

     // Migrate to version 2: Add a primary key + object references
     // Example:
     // public Person extends RealmObject {
     //     private String name;
     //     @PrimaryKey
     //     private int age;
     //     private Dog favoriteDog;
     //     private RealmList<Dog> dogs;
     //     // getters and setters left out for brevity
     // }
     if (oldVersion == 1) {
        schema.get("Person")
            .addField("id", long.class, FieldAttribute.PRIMARY_KEY)
            .addRealmObjectField("favoriteDog", schema.get("Dog"))
            .addRealmListField("dogs", schema.get("Dog"));
        oldVersion++;
     }
  }
}
'''

请查阅这个[数据迁移例子](https://github.com/realm/realm-java/tree/master/examples/migrationExample)来获取这方面的细节。

如果没有旧Realm数据文件存在,那么迁移并不需要,在这种情况下,Realm会创建一个新的以`.realm`为后缀,基于新的对象模型的数据文件。在开发和调试过程中,假如您需要频繁改变数据模型,_并且不介意损失旧数据_,您可以直接删除`.realm`文件(这里包含所有的数据!)而不用关心迁移的问题。这在您app的开发早期阶段非常有用。

```java
RealmConfiguration config = new RealmConfiguration.Builder(context)
    .deleteRealmIfMigrationNeeded()
    .build()
'''

## 加密

<!-- If article is non en then set the locale from the locale folder for i18n links  -->

<div class="alert alert-info">
  Please take note of the Export Compliance section of our LICENSE, as it places restrictions against the usage of Realm if you are located in countries with an export restriction or embargo from the United States.
</div>

Realm文件可以通过传递一个512位的密钥参数给`Realm.getInstance().encryptionKey()`来加密存储在磁盘上。

```java
byte[] key = new byte[64];
new SecureRandom().nextBytes(key);
RealmConfiguration config = new RealmConfiguration.Builder(context)
  .encryptionKey(key)
  .build();

Realm realm = Realm.getInstance(config);
'''

这保证了所有永久性存储在磁盘上的数据都是通过标准AES-256加密的。每次创建新的Realm实例的时候,都需要提供相同的密钥。

参考[examples/encryptionExample](https://github.com/realm/realm-java/tree/master/examples/encryptionExample)。这个例子演示了如何通过Android KeyStore来安全地存储密钥。

## 调试

当你使用 Android Studio 或者 IntelliJ 调试的时候请留神:调试视图中显示的变量值可能会造成误导。

举个例子,在 Android Studio 中查看一个`RealmObject`的所有属性。您会发现这些属性与期望不符。这时因为 Realm 为每个 RealmObject 创建了代理类,通过使用代理类的 getter 和 setter 方法来存取数据,从而原始对象的属性不会被赋值。请参考([更多信息](#section-4))。请查看访问器的返回以获得正确数据,入下图所示:

<img src="/assets/img/docs/java/realmobject-watch-panel.png" class="img-responsive img-rounded center-block" alt="Android Studio, IntelliJ Debug RealmObject" />

上图断点在113行。三个值被观察:`person` 变量,访问器`person.getName()` 和 `person.getAge()`。代码107行到111行改变了 `person` 实例的 name 和 age,这些值在事务中被持久化。当运行暂停在113行时,可以观察到,调试器中显示的 person 属性是不正确的,但是访问器`person.getName()` 和 `person.getAge()`的返回正确。请注意,`.toString()` 方法同样会输出正确的结果。

## 适配器(Adapter)

Realm提供了一个抽象的工具类来方便地将`RealmResult`展示到UI控件上。`RealmBaseAdapter`类帮您处理了大部分的工作,您只需要实现`getView()`方法。

<pre class="highlight java"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Person</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getName</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="k">this</span><span class="o">.</span><span class="na">name</span><span class="o">;</span>
    <span class="o">}</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">setName</span><span class="o">(</span><span class="n">String</span> <span class="n">name</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="n">name</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyAdapter</span> <span class="kd">extends</span> <span class="n">RealmBaseAdapter</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;</span> <span class="kd">implements</span> <span class="n">ListAdapter</span> <span class="o">{</span>

    <span class="kd">private</span> <span class="kd">static</span> <span class="kd">class</span> <span class="nc">MyViewHolder</span> <span class="o">{</span>
        <span class="n">TextView</span> <span class="n">name</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="nf">MyAdapter</span><span class="o">(</span><span class="n">Context</span> <span class="n">context</span><span class="o">,</span> <span class="kt">int</span> <span class="n">resId</span><span class="o">,</span>
                     <span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;</span> <span class="n">realmResults</span><span class="o">,</span>
                     <span class="kt">boolean</span> <span class="n">automaticUpdate</span><span class="o">)</span> <span class="o">{</span>
        <span class="kd">super</span><span class="o">(</span><span class="n">context</span><span class="o">,</span> <span class="n">realmResults</span><span class="o">,</span> <span class="n">automaticUpdate</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="n">View</span> <span class="nf">getView</span><span class="o">(</span><span class="kt">int</span> <span class="n">position</span><span class="o">,</span> <span class="n">View</span> <span class="n">convertView</span><span class="o">,</span> <span class="n">ViewGroup</span> <span class="n">parent</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">ViewHolder</span> <span class="n">viewHolder</span><span class="o">;</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">convertView</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">convertView</span> <span class="o">=</span> <span class="n">inflater</span><span class="o">.</span><span class="na">inflate</span><span class="o">(</span><span class="n">android</span><span class="o">.</span><span class="na">R</span><span class="o">.</span><span class="na">layout</span><span class="o">.</span><span class="na">simple_list_item_1</span><span class="o">,</span> 
                                           <span class="n">parent</span><span class="o">,</span> <span class="kc">false</span><span class="o">);</span>
            <span class="n">viewHolder</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ViewHolder</span><span class="o">();</span>
            <span class="n">viewHolder</span><span class="o">.</span><span class="na">name</span> <span class="o">=</span> <span class="o">(</span><span class="n">TextView</span><span class="o">)</span> <span class="n">convertView</span><span class="o">.</span><span class="na">findViewById</span><span class="o">(</span><span class="n">android</span><span class="o">.</span><span class="na">R</span><span class="o">.</span><span class="na">id</span><span class="o">.</span><span class="na">text1</span><span class="o">);</span>
            <span class="n">convertView</span><span class="o">.</span><span class="na">setTag</span><span class="o">(</span><span class="n">viewHolder</span><span class="o">);</span>
        <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
            <span class="n">viewHolder</span> <span class="o">=</span> <span class="o">(</span><span class="n">ViewHolder</span><span class="o">)</span> <span class="n">convertView</span><span class="o">.</span><span class="na">getTag</span><span class="o">();</span>
        <span class="o">}</span>

        <span class="n">Person</span> <span class="n">item</span> <span class="o">=</span> <span class="n">realmResults</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">position</span><span class="o">);</span>
        <span class="n">viewHolder</span><span class="o">.</span><span class="na">name</span><span class="o">.</span><span class="na">setText</span><span class="o">(</span><span class="n">item</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>
        <span class="k">return</span> <span class="n">convertView</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="n">RealmResults</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;</span> <span class="nf">getRealmResults</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">realmResults</span><span class="o">;</span>
    <span class="o">}</span>    
<span class="o">}</span></code></pre>



## 对其它库的支持

这个章节描述了怎样与其它Android流行库搭配使用Realm。

### GSON
[GSON](https://code.google.com/p/google-gson/) 是Google开发的JSON处理库. 当使用Realm配合GSON 2.3.1(最新版)时,您需要指定[ExclusionStrategy](http://google.github.io/gson/apidocs/com/google/gson/ExclusionStrategy.html)。

<pre class="highlight java"><code><span class="c1">// Using the User class</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">User</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">email</span><span class="o">;</span>
    <span class="c1">// getters and setters left out ...</span>
<span class="o">}</span>

<span class="n">Gson</span> <span class="n">gson</span> <span class="o">=</span> <span class="k">new</span> <span class="n">GsonBuilder</span><span class="o">()</span>
        <span class="o">.</span><span class="na">setExclusionStrategies</span><span class="o">(</span><span class="k">new</span> <span class="n">ExclusionStrategy</span><span class="o">()</span> <span class="o">{</span>
            <span class="nd">@Override</span>
            <span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">shouldSkipField</span><span class="o">(</span><span class="n">FieldAttributes</span> <span class="n">f</span><span class="o">)</span> <span class="o">{</span>
                <span class="k">return</span> <span class="n">f</span><span class="o">.</span><span class="na">getDeclaringClass</span><span class="o">().</span><span class="na">equals</span><span class="o">(</span><span class="n">RealmObject</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
            <span class="o">}</span>

            <span class="nd">@Override</span>
            <span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">shouldSkipClass</span><span class="o">(</span><span class="n">Class</span><span class="o">&lt;?&gt;</span> <span class="n">clazz</span><span class="o">)</span> <span class="o">{</span>
                <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
            <span class="o">}</span>
        <span class="o">})</span>
        <span class="o">.</span><span class="na">create</span><span class="o">();</span>

<span class="n">String</span> <span class="n">json</span> <span class="o">=</span> <span class="s">"{ name : 'John', email : 'john@corporation.com' }"</span><span class="o">;</span>
<span class="n">User</span> <span class="n">user</span> <span class="o">=</span> <span class="n">gson</span><span class="o">.</span><span class="na">fromJson</span><span class="o">(</span><span class="n">json</span><span class="o">,</span> <span class="n">User</span><span class="o">.</span><span class="na">class</span><span class="o">);</span></code></pre>


[GridViewExample](https://github.com/realm/realm-java/blob/master/examples/gridViewExample/src/main/java/io/realm/examples/realmgridview/GridViewExampleActivity.java)展示了如何配合GSON使用Realm。

#### 序列化(Serialization)

您有时需要序列化与反序列化一个Realm对象以便与其它库(比如[Retrofit](http://square.github.io/retrofit/))相配合。因为GSON[使用成员变量值而非getter和setter](https://groups.google.com/forum/#!topic/google-gson/4G6Lv9PghUY),所以您无法通过GSON的一般方法来序列化Realm对象。

你需要为Realm模型对象自定义一个[JsonSerializer](https://google.github.io/gson/apidocs/com/google/gson/JsonSerializer.html)并且将其注册为一个[TypeAdapter](https://google.github.io/gson/apidocs/com/google/gson/TypeAdapter.html)。

请参考[这个Gist](https://gist.github.com/cmelchior/ddac8efd018123a1e53a)。

#### 数组(Primitive lists)

某些JSON API会以数组的形式返回原始数据类型(例如String和integer),[Realm暂时不支持对这种数组的处理](https://github.com/realm/realm-java/issues/575)。但您可以通过自定义[TypeAdapter](https://google.github.io/gson/apidocs/com/google/gson/TypeAdapter.html)来处理这种情况。

[这个Gist](https://gist.github.com/cmelchior/1a97377df0c49cd4fca9)展示了如何将JSON中的整型数组存入Realm。类似地,您可以用这个方法来处理其它原始数据类型数组。

#### Troubleshooting

Realm 对象属性可能会包含循环引用。在这种情况下,GSON 会抛出 `StackOverflowError`。例如如下 Realm 对象拥有一个 `Drawable` 属性:

```java
public class Person extends RealmObject {
	@Ignore
	Drawable avatar;
	// other fields, etc
}
'''

`Person` 类含有一个 Androdi [`Drawable`](http://developer.android.com/reference/android/graphics/drawable/Drawable.html) 并且被 `@Ignore` 修饰。当 GSON 序列化时,Drawable 被读取并且造成了堆栈溢出。([GitHub Issue](https://github.com/realm/realm-java/issues/1798))。添加如下代码以避免类似问题:

```java
public boolean shouldSkipField(FieldAttributes f) {
  return f.getDeclaringClass().equals(RealmObject.class) || f.getDeclaringClass().equals(Drawable.class);
}
'''

请注意对 `Drawable.class` 的判定语句,它告诉 GSON 跳过这个属性的序列化以避免堆栈溢出错误。

### Otto
[Otto](http://square.github.io/otto/)是一个由[Square](https://github.com/square)开发的事件总线(event bus)。Otto与Realm搭配使用非常容易,但请注意时序和并发性的问题。

Otto通常使用同一个线程来收发事件,这意味着您可以将`RealmObject`作为事件参数并在接收器方法中处理。但您如果使用[这个方法](https://github.com/square/otto/issues/38)让Otto讲所有事件发送到UI线程执行,您就不可以再使用`RealmObject`做为事件参数了(`RealmObject`不能跨线程使用)。

当`RealmObject`在一个线程中被改变,Realm会在另一个线程中通过[Handler](http://developer.android.com/reference/android/os/Handler.html)更新Realm的数据。而`Otto.post(event)`会立刻调用事件处理。因此,当您发送Realm数据改变事件到其它线程,您需要手工调用`realm.refresh()`来得到最新的数据。

<pre class="highlight java"><code><span class="nd">@Subscribe</span>
<span class="kd">public</span> <span class="kt">void</span> <span class="nf">handleEvent</span><span class="o">(</span><span class="n">OttoEvent</span> <span class="n">event</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">realm</span><span class="o">.</span><span class="na">refresh</span><span class="o">();</span>
    <span class="c1">// Continue working with Realm data loaded in this thread</span>
<span class="o">}</span></code></pre>


### Parceler

[Parceler](https://github.com/johncarl81/parceler)可以帮助对象自动生成支持[Parcelable](http://developer.android.com/reference/android/os/Parcelable.html)接口的样板代码。因为Realm的代理类,您需要以下设置以便应用Parceler到Realm对象。

```java
// All classes that extend RealmObject will have a matching RealmProxy class created
// by the annotation processor. Parceler must be made aware of this class. Note that
// the class is not available until the project has been compiled at least once.
@Parcel(implementations = { PersonRealmProxy.class },
        value = Parcel.Serialization.BEAN,
        analyze = { Person.class })
public class Person extends RealmObject {
	// ...
}
'''

请注意目前在使用Parceler的时候有如下的限制:

1. 如果您的模型包含`RealmList`,那么您需要[注册一个特殊adapter](https://gist.github.com/cmelchior/72c35fcb55cec33a71e1)
2. 一旦对象被打包(parcelled),它将变为一个有当前数据快照,不再被Realm管理的一个standalone对象。之后该对象的数据变化不会被Realm写入。

### Retrofit
[Retrofit](http://square.github.io/retrofit/)是一个由[Square](https://github.com/square)开发,保证类型安全(typesafe)的REST API处理工具。

由于Retrofit内部使用[GSON](#gson),您需要定义一个GsonConverter以转换JSON数据到`RealmObject`。

<pre class="highlight java"><code><span class="n">Gson</span> <span class="n">gson</span> <span class="o">=</span> <span class="k">new</span> <span class="n">GsonBuilder</span><span class="o">()</span>
        <span class="o">.</span><span class="na">setExclusionStrategies</span><span class="o">(</span><span class="k">new</span> <span class="n">ExclusionStrategy</span><span class="o">()</span> <span class="o">{</span>
            <span class="nd">@Override</span>
            <span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">shouldSkipField</span><span class="o">(</span><span class="n">FieldAttributes</span> <span class="n">f</span><span class="o">)</span> <span class="o">{</span>
                <span class="k">return</span> <span class="n">f</span><span class="o">.</span><span class="na">getDeclaringClass</span><span class="o">().</span><span class="na">equals</span><span class="o">(</span><span class="n">RealmObject</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
            <span class="o">}</span>

            <span class="nd">@Override</span>
            <span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">shouldSkipClass</span><span class="o">(</span><span class="n">Class</span><span class="o">&lt;?&gt;</span> <span class="n">clazz</span><span class="o">)</span> <span class="o">{</span>
                <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
            <span class="o">}</span>
        <span class="o">})</span>
        <span class="o">.</span><span class="na">create</span><span class="o">();</span>

<span class="c1">// Configure Retrofit to use the proper GSON converter</span>
<span class="n">RestAdapter</span> <span class="n">restAdapter</span> <span class="o">=</span> <span class="k">new</span> <span class="n">RestAdapter</span><span class="o">.</span><span class="na">Builder</span><span class="o">()</span>
    <span class="o">.</span><span class="na">setEndpoint</span><span class="o">(</span><span class="s">"https://api.github.com"</span><span class="o">)</span>
    <span class="o">.</span><span class="na">setConverter</span><span class="o">(</span><span class="k">new</span> <span class="n">GsonConverter</span><span class="o">(</span><span class="n">gson</span><span class="o">))</span>
    <span class="o">.</span><span class="na">build</span><span class="o">();</span>

<span class="n">GitHubService</span> <span class="n">service</span> <span class="o">=</span> <span class="n">restAdapter</span><span class="o">.</span><span class="na">create</span><span class="o">(</span><span class="n">GitHubService</span><span class="o">.</span><span class="na">class</span><span class="o">);</span></code></pre>


Retrofit不会自动将对象添加到Realm,您必须通过[`realm.copyToRealm()`](api/io/realm/Realm.html#copyToRealm-java.lang.Iterable-)或[`realm.copyToRealmOrUpdate()`](api/io/realm/Realm.html#copyToRealmOrUpdate-java.lang.Iterable-) 方法来手动添加。

```java

GitHubService service = restAdapter.create(GitHubService.class);
List<Repo> repos = service.listRepos("octocat");

// Copy elements from Retrofit to Realm to persist them.
realm.beginTransaction();
List<Repo> realmRepos = realm.copyToRealmOrUpdate(repos);
realm.commitTransaction();

'''

### Robolectric
通过[Robolectric](http://robolectric.org)库可以让您在不使用真实设备或者模拟器的情况下直接在Java虚拟机上进行JUnit测试。但目前Roboletrics不支持带有原生库的测试。而Realm包含使用C++的原生库,所以您目前不可以通过Roboletrics测试使用Realm的项目。

你可以关注这个[Robolectric的新功能请求](https://github.com/robolectric/robolectric/issues/1389)。

### RxJava

[RxJava](https://github.com/ReactiveX/RxJava) 是 Netflix 发布的一个 [Reactive 的扩展](http://reactivex.io/) 库以支持 [观察者模式](https://en.wikipedia.org/wiki/Observer_pattern)。

Realm 包含了对 RxJava 的原生支持。如下类可以被暴露为一个[`Observable`](https://github.com/ReactiveX/RxJava/wiki/Observable):[`Realm`](api/io/realm/Realm.html#asObservable--), [`RealmResults`](api/io/realm/RealmResults.html#asObservable--), [`RealmObject`](api/io/realm/RealmObject.html#asObservable--), [`DynamicRealm`](api/io/realm/DynamicRealm.html#asObservable--) and [`DynamicRealmObject`](api/io/realm/DynamicRealmObject.html#asObservable--)。

```java
// Combining Realm, Retrofit and RxJava (Using Retrolambda syntax for brevity)
// Load all persons and merge them with their latest stats from GitHub (if they have any)
Realm realm = Realm.getDefaultInstance();
GitHubService api = retrofit.create(GitHubService.class);
realm.where(Person.class).isNotNull("username").findAllAsync().asObservable()
    .filter(persons.isLoaded)
    .flatMap(persons -> Observable.from(persons))
    .flatMap(person -> api.user(person.getGithubUserName())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(user -> showUser(user));

参考 RxJava sample project

Configuration

RxJava is an optional dependency, which means that Realm doesn’t automatically include it. This has the benefit that you can choose which version of RxJava to use as well as avoid the method count bloat in projects that does not use RxJava. RxJava has to be manually added to the build.gradle file.

dependencies {
  compile 'io.realm:realm-android:0.87.0'
  compile 'io.reactivex:rxjava:1.1.0'
}

It is possible to configure how Realm creates Observables by creating a custom RxObservableFactory. This is configured using RealmConfiguration.

RealmConfiguration config = new RealmConfiguration.Builder(context)
  .rxFactory(new MyRxFactory())
  .build()

If no RxObservableFactory is defined, Realm defaults to RealmObservableFactory which is a class provided by Realm that supports RxJava <= 1.1.*.

下一步

请参考我们的应用示例获取更多信息。

Happy hacking!欢迎在realm-java与我们真实存在的人类程序员交流!

目前的限制

Realm还处于beta阶段,我们一直在不断地修改bug及添加功能。在1.0版本的发布之前,Realm存在如下这些限制。

请参阅我们的GitHub issues获取更多关于已知问题的信息。

概要

Realm的目标是在可扩展性和运行效率之间取得一个平衡,因此在保存数据方面有一些客观存在的限制,例如:

  1. 类名长度的上限是57个字符。Realm-java在存储时会为对象名添加class_前缀,你可以通过Realm browser看到;
  2. 成员变量名长度上限是63个字符;
  3. Date的精度是1秒。
  4. 不支持嵌套事务(transaction),使用嵌套事务会导致抛出异常;
  5. Stringbyte []大小不能超过16MB;
  6. 忽略大小写查询所支持的字符集仅限于’Latin Basic’、’Latin Supplement’、’Latin Extended A’、’Latin Extended B’ (UTF-8 range 0-591);

对象

因为Realm生成的代理类会重载setter和getter,所以针对Realm对象有如下限制:

  • 只支持私有成员变量;
  • 只支持默认getter和setter方法;
  • 支持公有和私有静态变量;
  • 支持静态方法;
  • 支持接口实现。

这意味着您目前只能直接继承于RealmObject,不能重载其方法例如toString()或者equals()。您只可以实现接口。我们正在努力移除这些限制

排序

针对字符串的排序,只支持字符集’Latin Basic’、’Latin Supplement’、’Latin Extended A’、’Latin Extended B’ (UTF-8 range 0-591)。如果排序对象不在这些字符集的范围内,那么RealmResults的顺序并不会被改变。

忽略大小写查询

当使用equalTocontainendsWithbeginsWithcaseSensitive设置只针对英文环境(English locale)有效。参见这个问题

多线程

Realm数据文件本身支持多线程并发访问。但是Realm实例、RealmObjectRealmQuery以及RealmResults不可以跨线程使用。请参考多线程示例获取更多在多线程环境中使用Realm的信息。

Realm文件不支持多进程访问

尽管Realm文件支持多线程访问,但还不支持多进程访问。不同进程请使用不同的Realm文件拷贝。我们很快会提供对于多进程的支持。

最佳实践

防止出现 ANR

一般来说 Realm 的读写是足够快的,甚至在 UI 线程中读写也不是问题。但是,写事务是互相阻塞的,所以为了避免 ANR 的出现,我们建议你在后台线程中执行写操作。参考异步事务获得如何在后台线程进行写入相关的信息。

控制Realm实例的生命周期

RealmObjectsRealmResults在访问其引用数据时都是懒加载的。因为这个原因,请不要关闭你的Realm实例如果你仍然需要访问其中的Realm对象或者查询结果。为了避免不必要的Realm数据连接的打开和关闭,Realm内部有一个基于引用计数的缓存。这表示在同一线程内调用Realm.getDefaultInstance()多次是基本没有开销的,并且底层资源会在所有实例都关闭的时候才被释放。

以UI线程举例,最简单安全的途径是,在你所有的Activity和Fragment初始化时取得Realm实例,并在它们销毁时关闭Realm实例。

// Setup Realm in your Application
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this).build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
}

// onCreate()/onDestroy() overlap when switching between activities so onCreate()
// on Activity 2 will be called before onDestroy() on Activity 1.
public class MyActivity extends Activity {
    private Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        realm = Realm.getDefaultInstance();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close();
    }
}

// Use onStart()/onStop() for Fragments as onDestroy() might not be called.
public class MyFragment extends Fragment {
    private Realm realm;

    @Override
    public void onStart() {
        super.onStart();
        realm = Realm.getDefaultInstance();
    }

    @Override
    public void onStop() {
        super.onStop();
        realm.close();
    }
}
'''


### 重用RealmResultsRealmObjects

UI线程和其它包行Looper的线程中,`RealmObject`和`RealmResults`都会在Realm数据改变时自动刷新。这意味着你不需要在`RealmChangeListener`中重新获取这些对象。它们已经被更新并且准备好被重绘在屏幕上了。

```java
public class MyActivity extends Activity {

    private Realm realm;
    private RealmResults<Person> allPersons;
    private RealmChangeListener realmListener = new RealmChangeListener() {
        @Override
        public void onChange() {
            // Just redraw the views. `allPersons` already contain the
            // latest data.
            invalidateView();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        realm = Realm.getDefaultInstance();
        realm.addRealmChangeListener(listener);
        allPerson = realm.where(Person.class).findAll(); // Create the "live" query result
        setupViews(); // Initial setup of views
        invalidateView(); // Redraw views with data
    }

    // ...
}
'''

## FAQ

#### 我怎么才能查看我的Realm文件的数据?

[StackOverflow上的这个答案](http://stackoverflow.com/questions/28478987/how-to-view-my-realm-file-in-the-realm-browser)介绍了怎么找到您的Realm文件。您可以通过[Realm Browser](#realm-browser)来查看数据内容

#### Realm库有多大?

大部分情况下,在您release版本的apk文件里,Realm只占用800KB空间。我们发布的版本支持的处理器架构包括ARM7ARMv7ARM64x86MIPS。所以发布的库文件本身看起来会稍微大一些。但安卓系统在安装apk时只会安装针对该设备处理器架构的原生库,安装后占用空间会比apk文件本身还要小一些。

你可以通过将 APK 针对不同平台分离打包以减少其大小。 添加如下代码到 `build.gradle`:

```groovy
splits {
    abi {
        enable true
        reset()
        include 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'mips', 'x86', 'x86_64'
    }
}
'''

根据你设置的每个ABI,会生成一个独立 APK 文件。参考[Android Tools documentation](http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits)。

我们的这个实例也演示了同样的功能 [GitHub](https://github.com/realm/realm-java/tree/master/examples/gridViewExample)。

#### Realm能应用在生产环境中吗?

Realm2012年起就已经开始应用在商业生产环境中了。

请注意:我们会针对社区的反馈来调整接口,当然我们也会针对反馈来添加新的功能以及问题修正。

#### Realm是免费的吗?

是的!Realm安卓版本是完全免费的,包括使用在商业项目中。

#### 那你们怎么赚钱呢?

我们已经通过销售围绕我们的核心技术的产品和支持服务赚钱啦。如果您有额外的需求,欢迎通过[邮件](mailto:info@realm.io)与我们取得联系。我们会一如既往地在Apache 2.0许可下开发并支持[realm-java项目](http://github.com/realm/realm-java),它将永远作为一个开源项目存在。

#### 我经常在代码中看到`core`相关的字样,它是什么?

`core`是我们对于RealmC++存储引擎的称谓。这部分代码目前并没有开放。但基于Apache 2.0许可开源这部分代码在我们的计划之中。在我们清理并完善`core`的核心功能之前,这部分的二进制版本发布会基于[该许可](https://github.com/realm/realm-java/blob/master/LICENSE)。

#### 普通Java对象和Realm对象之间有什么区别?

主要区别在于普通Java对象本身会包含其数据,但Realm对象不会。Realm对象通过get或者set方法来直接从Realm数据库中存取数据。
也就是说:Realm对象总体上比普通Java对象更轻量;Realm对象在数据改变的时候会自动更新,而普通Java对象不会。

#### 为什么模型类需要继承于RealmObject

原因是我们需要针对模型类添加一些易用的接口,例如`removeFromRealm()`。另外它让我们比较容易在内部使用范型(generic)从而提高代码的易读性和易用性。

#### `RealmProxy`类是做什么用的?

我们使用RealmProxy类来保证Realm对象本身不存储任何实际的数据,进而通过直接访问Realm数据来存取数据。

对于您项目中的模型类,Realm的注解处理器(Annotation processor)会生成相应的RealmProxy类。该代理类继承于您的模型类,代理类是您在调用`Realm.createObject()`时实际返回的类型。

#### 我为什么要为每个字段生成gettersetter方法?

代理类依赖于gettersetter

代理类会重载gettersetter方法以便直接访问数据库存取数据。对于Java中私有成员变量来说这是唯一可行的方法。

这同时意味着当您在实现接口的时候(例如`Comparable`)也需要使用gettersetter来存取私有成员变量。

这并不是一个十分理想的方案。通过AspectJJavassist等其它一些途径有可能实现我们需要的功能,但我们还在研究这些可行性。

使用代理类使得您不可以在gettersetter中添加自己的代码逻辑。一个替代方案是您可以使用`@Ignore`来让Realm忽略某个字段,同时使用这个字段的gettersetter来添加您想要的代码逻辑。参考如下的例子:

<pre class="highlight java"><code><span class="kn">package</span> <span class="n">io</span><span class="o">.</span><span class="na">realm</span><span class="o">.</span><span class="na">entities</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">io.realm.RealmObject</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">io.realm.annotations.Ignore</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">StringOnly</span> <span class="kd">extends</span> <span class="n">RealmObject</span> <span class="o">{</span>

    <span class="kd">private</span> <span class="n">String</span> <span class="n">name</span><span class="o">;</span>

    <span class="nd">@Ignore</span>
    <span class="kd">private</span> <span class="n">String</span> <span class="n">kingName</span><span class="o">;</span>

    <span class="c1">// custom setter</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">setKingName</span><span class="o">(</span><span class="n">String</span> <span class="n">kingName</span><span class="o">)</span> <span class="o">{</span> <span class="n">setName</span><span class="o">(</span><span class="s">"King "</span> <span class="o">+</span> <span class="n">kingName</span><span class="o">);</span> <span class="o">}</span>

    <span class="c1">// custom getter</span>
    <span class="kd">public</span> <span class="n">String</span> <span class="nf">getKingName</span><span class="o">()</span> <span class="o">{</span> <span class="k">return</span> <span class="n">getName</span><span class="o">();</span> <span class="o">}</span>

    <span class="c1">// setter and getter for 'name'</span>
<span class="o">}</span></code></pre>


您可以使用`setKingName()`取代`setName()`来实现自己想要的功能。请注意,这里调用的`setName()`并不会直接对成员变量赋值。

#### 我为什么不能自己创建RealmObject?

Realm需要使用RealmObject的代理类来管理数据。

#### 我为什么需要使用事务(transaction)才能写入Realm数据库?

[Transactions](http://en.wikipedia.org/wiki/Database_transaction)是为了保证对数据的原子操作。它使得您可以保证多个数据被一次改变,或者保持不变。通过事务您可以精确控制您对每次需要改变多少数据(例如一次改变多个对象)。

基于SQL的数据库如SQLite,插入多条数据通常是被自动隐性包含在事务中一次完成的。但在Realm中,写入事务永远是显性的。

#### 怎么处理out-of-memory异常?

Realm基于我们的原生嵌入式存储引擎。该引擎会在原生内存堆(`native` memory)上而不是Java虚拟机的内存堆分配内存。如果您的应用在内存管理上的存在问题导致Realm无法分配内存,`io.realm.internal.OutOfMemoryError`异常会被抛出。请一定不要忽略这个异常!请不要使用空catch语句块来忽略这个异常!这么做有可能导致您的Realm数据库文件损坏!在该异常抛出时终止应用程序是不会损坏数据库的。如果您遇到了该异常,请检查应用是否有内存泄漏,或者其它内存使用异常的问题。

#### Realm数据库文件大小

一般来说,Realm数据文件比同等情况下的SQLite数据文件更小。

为了您数据的连续性,Realm会同时保存数据的不同版本。如果您在一个线程中读取了Realm数据之后阻塞了该线程,同时又在其它线程中写入了Realm,那么在第一个线程中的Realm不会被更新,并且因此一个非最新的Realm数据版本会被保存(这可能并不是您需要的数据)。以上会导致您的Realm文件体积增大(当然,Realm会重用这些额外的磁盘空间占用,或者您可以通过调用[`compactRealmFile`](api/io/realm/Realm.html#compactRealmFile)来释放这部分磁盘空间)。

#### 异常`Annotation processor may not have been executed.`是什么意思?

在编译过程中,Realm会针对模型类处理并生成相应的代理类。如果这个注解处理过程失败,模型类或者其方法在运行时无法被找到,那么就会抛出该异常。由于Java 6不支持注解(annotation)的继承,您需要在模型类之前添加`@RealmClass`。另外,请尝试删除或者清空编译结果,重新编译来解决这个问题。

#### Encryption is not supported on this device 异常

Realm的加解密功能曾经依赖于[Unix信号(signal)](https://en.wikipedia.org/wiki/Unix_signal),但是部分型号的设备(例如HTC One X)的[信号处理(signal handler)](https://en.wikipedia.org/wiki/Unix_signal)工作不正常。从`v0.82.2`版本开始,Realm会在打开或创建加密Realm时尝试探测运行其的设备是否存在这个问题。如果探测结果表明该设备无法使用加密Realm,`RealmEncryptionNotSupportedException`会被抛出。

从`v0.85.0`开始,Realm从新实现了底层的加解密机制,使其不再依赖Unix信号从而能够支持所有设备。因此`RealmEncryptionNotSupportedException`也从该版本起被移除。

#### 但我运行我的app时,看到有指向Mixpanel的网络连接,那是什么?

Realm在注解处理器运行的时候会收集匿名数据。我们保证这个过程是完全匿名的。它通过告诉我们你在使用哪个Realm版本、你的操作系统是什么帮助我们提高Realm的质量。**它不会在你的生产环境中执行,也不会在你的用户设备上执行。**它只会在注解处理器运行的时候执行。你可以在我们的[源代码](https://github.com/realm/realm-java/blob/master/realm/realm-annotations-processor/src/main/java/io/realm/processor/RealmAnalytics.java)中看到它具体收集了哪些信息。

#### Couldn't Load "librealm-jni.so"

如果你的app还包含其它原生库,并且它们没有提供对arm64平台的支持,arm64的安卓设备在加载Realm的`librealm-jni.so`时可能会失败。这是因为安卓无法同时加载32位和64位的原生库。最佳解决方案是为所有原生库提供arm64版本。但在你使用第三方闭源库的时候这不太好实现。参考[VLC and Realm Library conflicts](https://github.com/realm/realm-java/issues/1640)。

一个解决方案是在编译期通过配置gradleRealmarm64库排除在外:

android { //… packagingOptions { exclude “lib/arm64-v8a/librealm-jni.so” } //… } ```

更多信息请参考Mixing 32- and 64-bit Dependencies in Android